Django Create Model
Learn how to manage a new model in Django - free sample included.
This page explains how to create and USE a model in Django. All commands used to code the project and also the relevant updates are listed below. For newcomers, Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel.
Resources
​Support (Email and LIVE on Discord) for registered AppSeed users.
​

How to code this sample

This sample can be coded from scratch by following the steps below.
Check Python Version
1
$ python --version
2
Python 3.8.4 <-- All good
Copied!
Create/activate a virtual environment - Unix-based system
1
$ # Virtualenv modules installation
2
$ virtualenv env
3
$ source env/bin/activate
Copied!
For Windows, the syntax is slightly different
1
$ # virtualenv env
2
$ # .\env\Scripts\activate
Copied!
Install Django (the latest stable version)
1
$ pip install django
Copied!
Create a new Django Project
1
$ mkdir django-sample-urls
2
$ cd django-sample-urls
Copied!
Inside the new directory, we will invoke startproject subcommand
1
$ django-admin startproject config .
Copied!
Note: Take into account that . at the end of the command.
Setup the database
1
$ python manage.py makemigrations
2
$ python manage.py migrate
Copied!
Start the app
1
$ python manage.py runserver
2
$
3
$ # Access the web app in browser: http://127.0.0.1:8000/
Copied!
At this point we should see the default Django page in the browser:
Django - Default Project Page.
Create a new Django app
1
$ python manage.py startapp sample
Copied!
Visualize the default SQL settings - config/settings.py
1
# File: config/settings.py (partial content)
2
...
3
DATABASES = {
4
'default': {
5
'ENGINE': 'django.db.backends.sqlite3',
6
'NAME': BASE_DIR / 'db.sqlite3',
7
}
8
}
9
...
Copied!
Define a new model Books in sample application. The below changes should be added to sample/models.py:
1
# File: sample/models.py
2
​
3
from django.db import models
4
​
5
class Book(models.Model): # <- NEW
6
title = models.CharField(max_length=100) # <- NEW
7
author = models.CharField(max_length=100) # <- NEW
8
publication_date = models.DateField() # <- NEW
9
​
Copied!
Tip - for a quick check over the latest changes we can run check subcommand.
1
$ python manage.py check
2
System check identified no issues (0 silenced).
Copied!
Generate the SQL code (migrate the database).
1
$ python manage.py makemigrations # generate the SQL code
2
Migrations for 'sample':
3
sample\migrations\0001_initial.py
4
- Create model Book
Copied!
Apply changes on the database
1
$ python manage.py migrate
2
Operations to perform:
3
Apply all migrations: admin, auth, contenttypes, sample, sessions
4
Running migrations:
5
Applying sample.0001_initial... OK
Copied!
Use the model via CLI
Once the model is created we can use it via the Django shell:
1
$ python manage.py shell
2
>>>
3
>>> from sample.models import Book # import the Book model in our context
4
>>> from django.utils import timezone # used to provide the value for publication_date
5
>>>
6
>>> book1 = Book(title='The Adventures of Tom Sawyer', author='Mark Twain', publication_date=timezone.now() )
7
>>> book1.save() # save the new book
8
​
Copied!
List all books (using the CLI)
1
$ python manage.py shell
2
>>>
3
>>> from sample.models import Book
4
>>> Book.objects.all()
5
<QuerySet [<Book: Book object (1)>]>
Copied!
We can see our new book returned by the query. Let's improve the information that describes the object.
Django Model - add text representation of an object
To achieve this goal, we should define the __str__() method for the Book model
1
# File: sample/models.py
2
​
3
from django.db import models
4
​
5
class Book(models.Model):
6
title = models.CharField(max_length=100)
7
author = models.CharField(max_length=100)
8
publication_date = models.DateField()
9
​
10
def __str__(self): # <- NEW
11
return self.title # <- NEW
12
​
Copied!
Let's restart the Django console and check the results:
1
$ python manage.py shell
2
>>>
3
>>> from sample.models import Book
4
>>> Book.objects.all()
5
<QuerySet [<Book: The Adventures of Tom Sawyer>]>
6
​
Copied!
Use the model via Admin Section
Django comes with an admin section out-of-the-box that allows us to manage with ease all models defined in the project. To manage the Book model in the administration console we need to create a superuser (aka the admin) and after register the Book model to be visible in the admin section.
Create the superuser
1
$ python manage.py createsuperuser
2
sername (leave blank to use 'sm0ke'): admin
3
Email address: [email protected]
4
Password:
5
Password (again):
6
Superuser created successfully.
Copied!
Register Book model to be visible in the admin section - Edit sample/admin.py as below:
1
# File: sample/admin.py
2
​
3
from django.contrib import admin
4
​
5
from .models import Book # <- NEW
6
​
7
admin.site.register(Book) # <- NEW
Copied!
Authenticate as admin - http://localhost:8000/admin/
At this point, we should see the Books model in the UI and able to execute CRUD operations.
Create Django Model - Admin Interface.
Create Django Model - List Model Items
Django Create Model - Edit Model Item
​

Resources

Last modified 4mo ago