Skip to main content

Django CRUD Tutorial – Operations and Application Development....

What is CRUD?

CRUD stands for Create, Read, Update & Delete. These are the four basic operations which are executed on Database Models. We are developing a web app which is capable of performing these operations.
Since we are developing a library app, let’s take an example of the same. In a library, books are objects. The books have attributes like name, author, etc. We need an application which can perform CRUD operations on book object. The CRUD operations are defined as follows:
1. Read Operation
The ability of the application to read data from the database.
2. Create Operation
The ability of the application to store data in the database.
3. Update Operation
The ability of the application to edit the stored value in the database.
4. Delete Operation
The ability of the application to delete the value in the database.

1. Making a Library CRUD Application

Our first steps would be to make a new project in Django and a new virtual environment.

2. Installing Application and Other Important Settings

To install the app, just add the application’s name in the INSTALLED_APPS list. This is inside settings.py file.

3. Making Models for Books App

In the book folder, open models.py and paste this code. We are making a model or database table for our books app.

4. Making Model Forms in Book Directory

Django makes it so much easier to make forms for models. We just need to use our models and we can easily make forms.
Make a new file forms.py in book directory. Paste this code in this forms.py.

5. Registering Model in Django Admin

Here we are editing admin.py existing in book folder. Import the model you want to register in the admin. In this case, it is a Book.
Then paste this line below it.

Okay, so we have made a lot of backend here. To implement all of this, run these commands in the command line:

After running these commands, we also need a superuser to login to the admin. You can make a superuser using the command:
                           python manage.py createsuperuser                                           

6. Making View Functions for Django CRUD App

The view functions are our actual CRUD operations in Django. Now, we are editing views.py in book folder.
Open views.py file in the folder. Paste this code in it:


1. Index Function
This function is performing Read Operation. In this function, we simply retrieve all the objects in the book table. Those objects are then passed to the corresponding template.
We are using Querysets here for that purpose. As discussed in previous articles: Querysets is used to retrieve data from Tables. There are all kinds of filters and usage of Querysets and here we are using:
Book.objects.all()
It is clear from the query that it is passing a set of all objects in Book Table.
2. Upload Function
This function is CREATE operation of CRUD. It is simply taking form data from the user and saving it in a database. Since we made a model form for that, we don’t need to validate data again. We can directly save the form info in the database.
We first create the form object. Then we check whether the form is submitting data or user is visiting for the first time.
If the form request method is POST, it means the form is being submitted. You can see, it is also checked whether the form also has an image file or not. The request.FILES is a dictionary-like object containing the FILES and other information.
Then we check whether the data entered by the user is correct or not. This is done by form_object.is_clean() method. This will return True or False whether the form_object holds valid data or not.
If the answer is True, we save the form data received in the database. form_object.save() accomplishes this and since it’s a model form, we can use it directly.
If we receive a GET request then we return an empty form. That’s how we can create an object in the database.
3. Update_book Function
The update_book Function is a bit similar to the Update Function. It does more than that though. The update_book function takes in two parameters from the request. The request itself and id number. The id number is used to identify the object which is to be edited.
You can pass it in as a URL or as a cookie. The session method is the most secure but we don’t need to use it here. So, the update_book function will check whether the book_id is valid or not.
If the object exists it will return the form filled with the object’s information in it. The user can change the form again. In this case, there will be no creation of new book but the editing of the existing book object.
4. Delete Function
Delete Function is the last function of the CRUD application. We are again using the same object method as with Update book function. We are passing the request and book_id to delete the book.
This is a simpler interpretation of update_book function.
The queryset book.objects.get(id = book_id) will check for the books having an id equal to book_id. Since book_id is a primary key, we will have only one object returned. We can delete that object easily by just executing:
Book.delete() method. This will delete the book from the database.
So, these were the view functions. Now, we are ready to make the templates and complete our app.

7. Making Templates

The first thing you need to do is to make the templates folder in the book folder. Inside book/templates, make another folder book. We are going to make all our templates in that folder.
Inside book/templates/book, make a new file:
library.html

Understanding the Code:
It’s a simple template file where we are displaying objects from a database. We are running a for loop to access the data in the dictionary we passed. All the other things are CSS and some Bootstrap Framework.
                                             
                                                      Upload_form.html

Understanding the Code:
This is a typical form rendering template. We are using csrf token and other form tags. Here I am printing the form fields via for loop. This can be done in another way directly. It depends on how you want to render it in frontend.

8. Configuring URLs

Now, we need to configure the urls file. Paste this code as it is in the mentioned urls files. If the file doesn’t exist then make one and copy the whole thing.
Urls.py

                                                        Book/urls.py

This file contains all the URL lookups for library app as well as settings for Django static files. These settings are used by Django to render the images with the book object.

9. Running Server and Testing

At last, the fun part. To test the website, start your server by:
python manage.py runserver

Now, open the URL:
 http://127.0.0.1:8000/
You can see a page like this.
Home page - Django CRUD Example
Since I have already populated my data, it comes out like this.
Click on Upload book link on the top-right corner of the screen.
Upload books - Django CRUD Application
Here you can fill out the book information and submit it. If your book update is successful you should see a new edition on your homepage.
Now, taking the book objects from the homepage. Click on the edit button of one of the books.
Click on edit - Django CRUD App
As you will see, we will have a form filled with books information.
Book information form - Django CRUD Application
You can now change the information accordingly and submit again. This will change the data in the database.
Lastly, when you click the delete button in a book object, the book will be deleted from the database.
Deleted book
Now, there are only two books in the database. All these changes are occurring at the level of the database.




Comments

Post a Comment

Popular posts from this blog

How to fight with CoronaVirus ?

Basic protective measures against the new coronavirus Stay aware of the latest information on the COVID-19 outbreak, available on the WHO website and through your national and local public health authority. Most people who become infected experience mild illness and recover, but it can be more severe for others. Take care of your health and protect others by doing the following: Wash your hands frequently Regularly and thoroughly clean your hands with an alcohol-based hand rub or wash them with soap and water. Why?  Washing your hands with soap and water or using alcohol-based hand rub kills viruses that may be on your hands. Maintain social distancing Maintain at least 1 metre (3 feet) distance between yourself and anyone who is coughing or sneezing. Why?  When someone coughs or sneezes they spray small liquid droplets from their nose or mouth which may contain virus. If you are too close, you can breathe in the droplets, including the COVID-

Why python?

Beginner Friendliness Python was designed to be easy to understand and fun to use (its name came from Monty Python so a lot of its beginner tutorials reference it). Fun is a great motivator, and since you'll be able to build prototypes and tools quickly with Python, many find coding in Python a satisfying experience. Thus, Python has gained popularity for being a beginner-friendly language, and it has replaced Java as the  most popular introductory language at Top U.S. Universities . Easy to Understand Being a very high level language, Python reads like English, which takes a lot of syntax-learning stress off coding beginners. Python handles a lot of complexity for you, so it is very beginner-friendly in that it allows beginners to focus on learning programming concepts and not have to worry about too much details. Very Flexible As a dynamically typed language, Python is really flexible. This means there are no hard rules on how to build features, and you'll

Focus on These 4 Successful Mindsets to Rise to the Top..

Mindset No. 1: Start, Then Finish You have all you need to achieve your goals. You’re driven, geared up, and you don’t mind doing the work to get there. In fact, you’re looking forward to it. So, when exciting projects and collaborations enter your radar, you say yes — to all of them. You think being successful is about having lots of amazing projects going on at the same time. I hate to be the one to tell you this, but you’re wrong. I was quite competitive in my early career, always eager to take on new projects with high goals. Sometimes I got really lucky and hit my goals, but I used to fail a lot more than I used to win. I realized after some time that it wasn’t because of a lack of skills or knowledge. I wasn’t focusing on the things that really mattered. Truly successful people are very careful about choosing what projects to work on. Their main focus is to follow through and finish what they start. No matter how good the project, no matter how great the idea, you w