3 Steps For Creating Model in Django
3 Steps For Creating Model in Django
python --version
If Python is installed, you will get a result with the version number, like this
Python 3.9.2
If you find that you do not have Python installed on your computer, then you
can download it for free from the following website: https://www.python.org/
PIP
To install Django, you must use a package manager like PIP, which is
included in Python from version 3.4.
To check if your system has PIP installed, run this command in the command
prompt:
pip --version
If PIP is installed, you will get a result with the version number.
If you do not have PIP installed, you can download and install it from this
page: https://pypi.org/project/pip/
Virtual Environment
It is suggested to have a dedicated virtual environment for each Django
project
1|Page
nd one way to manage a virtual environment is venv, which is included in
Python.
The name of the virtual environment is your choice, in this tutorial we will
call it myworld.
Windows:
py -m venv myworld
Unix/MacOS:
This will set up a virtual environment, and create a folder named "myworld"
with subfolders and files, like this:
myworld
Include
Lib
Scripts
pyvenv.cfg
Windows:
myworld\Scripts\activate.bat
Unix/MacOS:
source myworld/bin/activate
Once the environment is activated, you will see this result in the command
prompt:
Windows:
Unix/MacOS:
(myworld) ... $
Note: You must activate the virtual environment every time you open the
command prompt to work on your project.
2|Page
Install Django
Now, that we have created a virtual environment, we are ready to install
Django.
Note: Remember to install Django while you are in the virtual environment!
Windows:
Unix/MacOS:
Which will give a result that looks like this (at least on my Windows
machine):
Collecting Django
Downloading Django-4.0.3-py3-none-any.whl (8.0 MB)
|████████████████████████████████| 8.0 MB 2.2 MB/s
Collecting sqlparse>=0.2.2
Using cached sqlparse-0.4.2-py3-none-any.whl (42 kB)
Collecting asgiref<4,>=3.4.1
Downloading asgiref-3.5.0-py3-none-any.whl (22 kB)
Collecting tzdata; sys_platform == "win32"
Downloading tzdata-2021.5-py2.py3-none-any.whl (339 kB)
|████████████████████████████████| 339 kB 6.4 MB/s
Installing collected packages: sqlparse, asgiref, tzdata, Django
Successfully installed Django-4.0.3 asgiref-3.5.0 sqlparse-0.4.2
tzdata-2021.5
WARNING: You are using pip version 20.2.3; however, version 22.3 is
available.
You should consider upgrading via the 'C:\Users\Your
Name\myworld\Scripts\python.exe -m pip install --upgrade pip' command.
That's it! Now you have installed Django in your new project, running in a
virtual environment!
Windows:
py --version
Unix/MacOS:
python --version
If Django is installed, you will get a result with the version number:
4.1.2
my_tennis_club
manage.py
my_tennis_club/
4|Page
__init__.py
asgi.py
settings.py
urls.py
wsgi.py
These are all files and folders with a specific meaning, you will learn about
some of them later in this tutorial, but for now, it is more important to know
that this is the location of your project, and that you can start building
applications in it.
py manage.py runserver
You have 18 unapplied migration(s). Your project may not work properly
until you apply the migrations for app(s): admin, auth, contenttypes,
sessions.
Run 'python manage.py migrate' to apply them.
October 27, 2022 - 13:03:14
Django version 4.1.2, using settings 'my_tennis_club.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Open a new browser window and type 127.0.0.1:8000 in the address bar.
The result:
5|Page
Django Create App
What is an App?
An app is a web application that has a specific meaning in your project, like a
home page, a contact form, or a members database.
In this tutorial we will create an app that allows us to list and register
members in a database.
But first, let's just create a simple Django app that displays "Hello World!".
Create App
I will name my app members.
Start by navigating to the selected location where you want to store the app,
in my case the my_tennis_club folder, and run the command below.
6|Page
If the server is still running, and you are not able to write commands, press
[CTRL] [BREAK], or [CTRL] [C] to stop the server and you should be back in
the virtual environment.
my_tennis_club
manage.py
my_tennis_club/
members/
migrations/
__init__.py
__init__.py
admin.py
apps.py
models.py
tests.py
views.py
These are all files and folders with a specific meaning. You will learn about
most of them later in this tutorial.
Django Views
Views
Django views are Python functions that takes http requests and returns http
response, like HTML documents.
A web page that uses Django is full of views with different tasks and
missions.
Views are usually put in a file called views.py located on your app's folder.
my_tennis_club/members/views.py:
7|Page
# Create your views here.
Find it and open it, and replace the content with this:
my_tennis_club/members/views.py:
def members(request):
Note: The name of the view does not have to be the same as the
application.
Django URLs
Create a file named urls.py in the same folder as the views.py file, and type
this code in it:
my_tennis_club/members/urls.py:
urlpatterns = [
8|Page
The urls.py file you just created is specific for the members application. We
have to do some routing in the root directory my_tennis_club as well. This may
seem complicated, but for now, just follow the instructions below.
There is a file called urls.py on the my_tennis_club folder, open that file and
add the include module in the import statement, and also add a path() function
in the urlpatterns[] list, with arguments that will route users that comes in
via 127.0.0.1:8000/.
my_tennis_club/my_tennis_club/urls.py:
urlpatterns = [
path('', include('members.urls')),
path('admin/', admin.site.urls),
If the server is not running, navigate to the /my_tennis_club folder and execute
this command in the command prompt:
py manage.py runserver
9|Page
Django Templates
Templates
In the Django Intro page, we learned that the result should be in HTML, and
it should be created in a template, so let's do that.
Create a templates folder inside the members folder, and create a HTML file
named myfirst.html
my_tennis_club
manage.py
my_tennis_club/
members/
templates/
myfirst.html
my_tennis_club/members/templates/myfirst.html:
10 | P a g e
<!DOCTYPE html>
<html>
<body>
<h1>Hello World!</h1>
</body>
</html>
my_tennis_club/members/views.py:
def members(request):
template = loader.get_template('myfirst.html')
return HttpResponse(template.render())
Change Settings
To be able to work with more complicated stuff than "Hello World!", We have
to tell Django that a new app is created.
Look up the INSTALLED_APPS[] list and add the members app like this:
11 | P a g e
my_tennis_club/my_tennis_club/settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'members'
Copy path of your template directory and paste under TEMPLATES section in
seetings.py
'DIRS': ['F:/djangobasicproject/my_tennis_club/members/templates'],
py manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
12 | P a g e
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying auth.0012_alter_user_first_name_max_length... OK
Applying sessions.0001_initial... OK
Start the server by navigating to the /my_tennis_club folder and execute this
command:
py manage.py runserver
13 | P a g e
Django Models
A Django model is a table in your database.
Django Models
Up until now, output has been static data from Python or HTML templates.
Now we will see how Django allows us to work with data, without having to
change or upload files in the process.
Open it, and add a Member table by creating a Member class, and describe the
table fields in it:
my_tennis_club/members/models.py:
class Member(models.Model):
firstname = models.CharField(max_length=255)
lastname = models.CharField(max_length=255)
The first field, firstname, is a Text field, and will contain the first name of the
members.
The second field, lastname, is also a Text field, with the member's last name.
14 | P a g e
SQLite Database
When we created the Django project, we got an empty SQLite database.
By default, all Models created in the Django project will be created as tables
in this database.
Migrate
Now when we have described a Model in the models.py file, we must run a
command to actually create the table in the database.
Django creates a file describing the changes and stores the file in
the /migrations/ folder:
my_tennis_club/members/migrations/0001_initial.py:
class Migration(migrations.Migration):
15 | P a g e
initial = True
dependencies = [
operations = [
migrations.CreateModel(
name='Member',
fields=[
('id', models.BigAutoField(auto_created=True,
primary_key=True, serialize=False, verbose_name='ID')),
('firstname', models.CharField(max_length=255)),
('lastname', models.CharField(max_length=255)),
],
),
Note that Django inserts an id field for your tables, which is an auto increment
number (first record gets the value 1, the second record 2 etc.), this is the
default behavior of Django, you can override it by describing your
own id field.
The table is not created yet, you will have to run one more command, then
Django will create and execute an SQL statement, based on the content of
the new file in the /migrations/ folder.
py manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, members, sessions
Running migrations:
Applying members.0001_initial... OK
16 | P a g e
Now you have a Member table in you database!
View SQL
As a side-note: you can view the SQL statement that were executed from the
migration above. All you have to do is to run this command, with the
migration number:
BEGIN;
--
-- Create model Member
--
CREATE TABLE "members_member" ("id" integer NOT NULL PRIMARY KEY
AUTOINCREMENT, "firstname" varchar(255) NOT NULL, "lastname"
varchar(255) NOT NULL); COMMIT;
We will use the Python interpreter (Python shell) to add some members to it.
py manage.py shell
Now we are in the shell, the result should be something like this:
17 | P a g e
>>> from members.models import Member
Hit [enter] and write this to look at the empty Member table:
>>> Member.objects.all()
<QuerySet []>
>>> Member.objects.all().values()
18 | P a g e
>>> member5.save()
>>> members_list = [member1, member2, member3, member4, member5]
>>> for x in members_list:
>>> x.save()
>>> Member.objects.all().values()
<QuerySet [{'id': 1, 'firstname': 'Emil', 'lastname': 'Refsnes'},
{'id': 2, 'firstname': 'Tobias', 'lastname': 'Refsnes'},
{'id': 3, 'firstname': 'Linus', 'lastname': 'Refsnes'},
{'id': 4, 'firstname': 'Lene', 'lastname': 'Refsnes'},
{'id': 5, 'firstname': 'Stale', 'lastname': 'Refsnes'},
{'id': 6, 'firstname': 'Jane', 'lastname': 'Doe'}]>
x will now represent the member at index 4, which is "Stale Refsnes", but to
make sure, let us see if that is correct:
>>> x.firstname
'Stale'
>>> Member.objects.all().values()
19 | P a g e
Hopefully, the result will look like this:
x will now represent the member at index 5, which is "Jane Doe", but to
make sure, let us see if that is correct:
>>> x.firstname
'Jane'
>>> x.delete()
Which tells us how many items were deleted, and from which Model.
If we look at the Member Model, we can see that 'Jane Doe' is removed from
the Model:
20 | P a g e
>>> Member.objects.all().values()
<QuerySet [{'id': 1, 'firstname': 'Emil', 'lastname': 'Refsnes'},
{'id': 2, 'firstname': 'Tobias', 'lastname': 'Refsnes'},
{'id': 3, 'firstname': 'Linus', 'lastname': 'Refsnes'},
{'id': 4, 'firstname': 'Lene', 'lastname': 'Refsnes'},
{'id': 5, 'firstname': 'Stalikken', 'lastname': 'Refsnes'}]>
>>> exit()
my_tennis_club/members/models.py:
class Member(models.Model):
firstname = models.CharField(max_length=255)
lastname = models.CharField(max_length=255)
phone = models.IntegerField()
joined_date = models.DateField()
As you can see, we want to add phone and joined_date to our Member Model.
Which, in my case, will result in a prompt, because I try to add fields that are
not allowed to be null, to a table that already contains records.
As you can see, Django asks if I want to provide the fields with a specific
value, or if I want to stop the migration and fix it in the model:
21 | P a g e
py manage.py makemigrations members
You are trying to add a non-nullable field 'joined_date' to members
without a default; we can't do that (the database needs something to
populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows
with a null value for this column)
2) Quit, and let me add a default in models.py
Select an option:
I will select option 2, and open the models.py file again and allow NULL values
for the two new fields:
my_tennis_club/members/models.py:
class Member(models.Model):
firstname = models.CharField(max_length=255)
lastname = models.CharField(max_length=255)
phone = models.IntegerField(null=True)
joined_date = models.DateField(null=True)
py manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, members, sessions
Running migrations:
Applying members.0002_member_joined_date_member_phone... OK
22 | P a g e
(myworld) C:\Users\Your Name\myworld\my_tennis_club>
Insert Data
We can insert data to the two new fields.
py manage.py shell
Now we are in the shell, the result should be something like this:
At the bottom, after the three >>> write the following (and hit [enter] for each
line):
This will insert a phone number and a date in the Member Model, at least for
the first record, the four remaining records will for now be left empty. We will
deal with them later in the tutorial.
>>> Member.objects.all().values()
<QuerySet [
{'id': 1, 'firstname': 'Emil', 'lastname': 'Refsnes', 'phone': 5551234,
'joined_date': datetime.date(2022, 1, 5)},
{'id': 2, 'firstname': 'Tobias', 'lastname': 'Refsnes', 'phone': None,
'joined_date': None},
{'id': 3, 'firstname': 'Linus', 'lastname': 'Refsnes', 'phone': None,
'joined_date': None},
23 | P a g e
{'id': 4, 'firstname': 'Lene', 'lastname': 'Refsnes', 'phone': None,
'joined_date': None},
{'id': 5, 'firstname': 'Stalikken', 'lastname': 'Refsnes', 'phone':
None, 'joined_date
my_tennis_club/members/templates/all_members.html:
<!DOCTYPE html>
<html>
<body>
<h1>Members</h1>
<ul>
{% for x in mymembers %}
{% endfor %}
</ul>
</body>
</html>
24 | P a g e
Do you see the {% %} brackets inside the HTML document?
They are Django Tags, telling Django to perform some programming logic
inside these brackets.
Modify View
Next we need to make the model data available in the template. This is done
in the view.
In the view we have to import the Member model, and send it to the template
like this:
my_tennis_club/members/views.py:
def members(request):
mymembers = Member.objects.all().values()
template = loader.get_template('all_members.html')
context = {
'mymembers': mymembers,
Creates a mymembers object with all the values of the Member model.
Loads the all_members.html template.
Creates an object containing the mymembers object.
Sends the object to the template.
Outputs the HTML that is rendered by the template.
25 | P a g e
The Result
If you have followed all the steps on your own computer, you can see the
result in your own browser:
py manage.py runserver
26 | P a g e