Create DataCreate Data

In this section, we will consider the 4 main operations with the database (CRUD):

  • Create data.
  • Retrieve data.
  • Update data.
  • Delete data.

As mentioned earlier, instances of the Model class are records in the table of the database.


To work with the database, you need to understand one thing: the code of our project runs independently of the database, so any changes in the database must be submitted.

For instances of the Model class, the save() method is a way to submit changes in data in the database.

Changes in database structureChanges in data
makemigrations and migrate in TerminalThe save() method for the instances of Model class

We implement the Post model. As you know, in any social network, there are posts that users use, so this example will be useful because it can often be used in real development.

First, we need to implement the model of posts.


Do not forget about migrations.

A new table is created empty. Let's consider how it can be filled.

As you already remember, Views are functions (or classes) that execute when receiving an HTTP request. Now let's create a new View inside the file to execute the code using the IDE to better consider working with the database.

The provided code defines a function named post_create that handles a request and performs the creation of a new post in a database. The code creates a new instance of the Post model, sets the title and text attributes of the post, saves it to the database using the save() method, and finally returns an HTTP response with the message "Complete!" rendered as a level one heading.


  • The save() method submits changes and applies them to the database.
  • The post id is defined when save() method is executed.

Now we need to connect this view to the URL.
In the file let's write the following URL pattern:

The provided code configures URL routing. It imports the post_create view function from the new_app.views module. URL pattern is defined, which maps the URL path posts/create/ to the post_create view function, and assigns the name "post-create" to this URL pattern for easy reference in other parts of the Django project.


Let's run server and see the result using the URL.

The header has returned, so the View is executed. Let's look at the database.

You can see the record in the database was created.
Let's repeat our request to the same URL.

We added 4 of the same posts. Now you know how to fill the database.


The steps to add record in the database:

  1. Import the Model class.
  2. Create the instance of this Model class.
  3. Fill in the attributes of this instance.
  4. Use the save() method to apply changes.


How to create a record in the database (apply changes)?

Select the correct answer

Everything was clear?

Section 4. Chapter 1