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.
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.
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.
As you will see, we will have a form filled with books information.
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.
Now, there are only two books in the database. All these changes are occurring at the level of the database.
Very good
ReplyDeleteThanks 😊
Delete