ToDo App in Django Part 2: Creating Model in Django for ToDo App

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.

Creating Model

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 False here.
  • created: This datetime indicates when the task was created. Since you are using auto_now_add here, 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.

The 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 makemigrations command.

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:

django administration, creating model in django, todo app in django

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:

django admin

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:

tasks model added, creaing model for todo app in django, todo app tutorial in django

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.

adding task from admin site

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:

task will display

That’s it. In the next tutorial, we will see about views, urls, templates, and more.

Previous: ToDo App in Django Part 1: Django Installation and Setup

Next: ToDo App in Django Part 3: URLs, View, and Template in Django

Leave a Comment

Copy link
Powered by Social Snap