Hello awesome people, welcome to the Learn Django by Doing Project Series. In the previous tutorial, we have seen the installation of Django and the setup of the project.
Today we create a model for our app to store our task in the database. So let’s start. Before that, activate your virtual environment in your project path.
You will start designing your Task data schema by defining the data models for your todolist app. A model is a Python class that subclasses
django.db.models.Model in which each attribute represents a database field. Django will create a table for each model defined in the models.py file. By default SQLite database used to store data.
First, you need to define a Task model. Add the following lines to the models.py file of the todolist application:
from django.db import models # Create your models here. class Task(models.Model): title=models.CharField(max_length=350) completed=models.BooleanField(default=False) created=models.DateTimeField(auto_now_add=True) def __str__(self): return self.title
This is your data model for todolist. Let’s take a look at the fields you just defined
for this model:
- title: This is the field for the task title. This field is
CharField, which translates into a VARCHAR column in the SQL database.
- completed: This field indicates, is task is completed or not. By default, we set
- created: This datetime indicates when the task was created. Since you are using
auto_now_addhere, the date will be saved automatically when creating an object.
- Here we don’t make primary key, Django model creates automatically for you. you can access it with pk or id.
The __str__() method is the default human-readable representation of the object. Django will use it in many places, such as the administration site.
Creating and applying migrations
Now the model is ready for your todolist app to store tasks. You will need a database table for it. Django comes with a migration system that tracks the changes made to the model and enables them to propagate into the database.
migrate command applies migrations for all applications listed in INSTALLED_APP in settings.py. It synchronizes the database with the current models and existing migrations.
First, you will need to create an initial migration for your Task model. In the root directory of your project, run the following command:
python3 manage.py makemigrations
You should get the following output:
Migrations for 'todolist': todolist/migrations/0001_initial.py - Create model Task
Let’s sync your database with the new model. Run the following command to apply existing migrations:
python3 manage.py migrate
You just applied migrations for the applications listed in INSTALLED_APPS, including your todolist application. After applying the migrations, the database reflects the current status of your models.
If you edit the models.py file in order to add, remove, or change the fields of existing models, or if you add new models, you will have to create a new migration using the
The migration will allow Django to keep track of model changes. Then, you will have to apply it with the
migrate command to keep the database in sync with your models.
Creating a superuser
Now that you have defined the Task model, you will create a simple administration site to manage your todo app.
Django comes with a built-in administration interface that is very useful for editing content. The Django site is built dynamically by reading your model metadata and providing a production-ready interface for editing content.
You can use it out of the box, configuring how you want your models to be displayed in it.
The django.contrib.admin application is already included in the INSTALLED_APPS setting, so you don’t need to add it.
First, you will need to create a user to manage the administration site. Run the following command:
python3 manage.py createsuperuser
After this, you will see the following output. Enter your desire username, email, and password as follows:
Username (leave blank to use 'arpit'): admin Email address: [email protected] Password: ***** Password (again): ***** This password is too short. It must contain at least 8 characters. This password is too common. This password is entirely numeric. Bypass password validation and create user anyway? [y/N]: y Superuser created successfully.
The Django administration site
We created a superuser. Now, start the development server using
python3 manage.py runserver command and open
http://127.0.0.1:8000/admin/ in your favorite browser.
You should see the administration login page, as shown in the following screenshot:
Login using the credentials of the user you created in the preceding step. You will see the administration site index page, as shown in the following screenshot:
The Group and User models are part of the Django authentication framework located in
django.contrib.auth. If you click on Users, you will see the user you created previously.
Adding models to the administration site
Now we are adding our Task model to the administration site. For that open admin.py file of the todolist app and add this:
from django.contrib import admin from .models import Task # Register your models here. admin.site.register(Task)
Now open or reload the administration site in your browser. You should see your Task model on the site, as follows:
That was easy, right? When you register a model in the Django administration site, you get a user-friendly interface generated by introspecting your models that allows you to list, edit, create and delete objects in a simple way.
Now just open the Tasks and click on the ADD TASK link on the top-right corner and then you will get this.
Fill in the form and click on the SAVE button. You should be redirected to the task list page with a success message and the task you just created, as shown in the following screenshot:
That’s it. In the next tutorial, we will see about views, urls, templates, and more.