Django for Beginners #3 - The CRUD Operations
- Django for Beginners #1
- Django for Beginners #2
- Django for Beginners #3 ← You are here
- Django for Beginners #4
- Django for Beginners #5
We introduced many new concepts in the previous articles, and you probably feel a bit lost. But don’t worry, in this article, we will dig deeper and find out how the URL dispatchers, models, views, and templates can work together to create a functional Django application.
To make things easier to understand, in this article, we are not going to create a full-featured blog application with categories, tags and etc. Instead, we will create only a post page that displays a post article, a home page that shows a list of all articles, and a create/update/delete page that modifies the post.
➡️ Get the source code for FREE!
Designing the database structure #
Let’s start with the model layer. The first thing you need to do is design the database structure. Since we are only dealing with posts right now, you can go ahead to the models.py
file, and create a new Post
model:
blog/models.py
|
|
This Post
contains only two fields, title
, which is a CharField
with a maximum of 100 characters, and content
, which is a TextField
.
Generate the corresponding migration files with the following command:
|
|
Apply the migrations:
|
|
The CRUD operations #
Now, it is time for us to dive into the application itself. When building real-life applications, it is unlikely for you to create all the controllers first, and then design the templates, and then move on to the routers. Instead, you need to think from the user’s perspective, and think about what actions the user might want to take.
In general, the user should have the ability to perform four operations on each resource, which in our case, is the Post
.
- Create: This operation is used to insert new data into the database.
- Read: This operation is used to retrieve data from the database.
- Update: This operation is used to modify existing data in the database.
- Delete: This operation is used to remove data from the database.
Together, they are referred to as the CRUD operations.
The create action #
First, let’s start with the create action. Currently, the database is still empty, so the user must create a new post. To complete this create action, you need a URL dispatcher that points the URL pattern /post/create/
to the post_create()
view function.
The post_create()
view function should have a flow control (if
statement), if the request method is GET
, return a template that contains an HTML form, allowing the user to pass information to the backend (form submission should be a POST
request). If the request method is POST
, a new Post
resource should be created and saved.
Here is a brief review on HTTP methods in case you need a refresher:
- The
GET
method is the most commonly used HTTP request method. It is used to request data and resources from the server.- The
POST
method is used to send data to the server, used for creating/updating a resource.- The
HEAD
method works just like theGET
method. Except the HTTP response will only contain the head and not the body. This method is usually used by developers for debugging purposes.- The
PUT
method is similar toPOST
, with one small difference. When youPOST
a resource that already exists on the server, this action would not cause any difference. ThePUT
method, however, will duplicate that resource, every time you make the request.- The
DELETE
method removes a resource from the server.
Let us start with the URL dispatcher, go to urls.py
:
djangoBlog/urls.py
|
|
Then you’ll need a post_create()
view function. Go to views.py
and add the following code:
blog/views.py
|
|
The post_create()
function first examines the method of the HTTP request, if it is a GET
method, return the create.html
template, if it is a POST
, use the information passed by that POST
request to create a new Post
instance, and after it is done redirect to the home page (we’ll create this page in the next step).
Next, time to create the create.html
template. First of all, you need a layout.html
:
templates/layout.html
|
|
Notice the {% url 'create' %}
on line 22. This is how you can reverse resolute URLs based on their names. The name create
matches the name you gave to the post/create/
dispatcher.
I also added TailwindCSS through a CDN on line 8 to make this page look better, but you shouldn’t do this in the production environment.
Next, create the create.html
template. I choose to create a post
directory for it to make it clear that this template is for creating a post, but you can do this differently as long as it makes sense to you:
templates/post/create.html
|
|
Line 10 specifies the action this form will take when it is submitted, and the request method it will use.
Line 11 adds CSRF protection to the form for security purposes.
Also pay attention to the <input>
field on line 13 and 14. Its name
attribute is very important. When the form is submitted, the user input will be tied to this name attribute, and you can then retrieve that input in the view function like this:
|
|
Same for the <textarea>
on line 17 and 18.
And finally, the button must have type="submit"
for it to work.
The list action #
Now let’s create a home page where you can show a list of all posts. You can start with the URL again:
djangoBlog/urls.py
|
|
And then the view function:
blog/views.py
|
|
The list.html
template:
|
|
The {% for post in posts %}
iterates over all posts
, and each item is assigned to the variable post
.
The {% url 'show' post.pk %}
passes the primary key of the post
to the show
URL dispatcher, which we’ll create later.
And finally, {{ post.content | truncatewords:50 }}
uses a filter truncatewords
to truncate the content
to the first 50 words.
The show action #
Next, the show action should display the content of a particular post, which means its URL should contain something unique that allows Django to locate just one Post
instance. That something is usually the primary key.
djangoBlog/urls.py
|
|
The integer following post/
will be assigned to the variable id
, and passed to the view function.
blog/views.py
|
|
And again, the corresponding template:
templates/post/show.html
|
|
The update action #
The URL dispatcher:
djangoBlog/urls.py
|
|
The view function:
blog/views.py
|
|
The update_or_create()
method is a new method added in Django 4.1.
The corresponding template:
templates/post/update.html
|
|
The delete action #
Finally, for the delete action:
djangoBlog/urls.py
|
|
blog/views.py
|
|
This action does not require a template, since it just redirects you to the home page after the action is completed.
Start the server #
Finally, let’s start the dev server and see the result.
|
|
The home page:
The create page:
The show page:
The update page:
If you think my articles are helpful, please consider making a donation to me. Your support is greatly appreciated.