0% found this document useful (0 votes)
3 views71 pages

Django Models

This document is a comprehensive tutorial on Django, a Python-based web framework that simplifies web development. It covers installation, project setup, creating apps, and the MVT design pattern, along with practical examples and exercises. The tutorial also includes instructions for using templates, views, and URLs to build a functional web application.

Uploaded by

susuela
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views71 pages

Django Models

This document is a comprehensive tutorial on Django, a Python-based web framework that simplifies web development. It covers installation, project setup, creating apps, and the MVT design pattern, along with practical examples and exercises. The tutorial also includes instructions for using templates, views, and URLs to build a functional web application.

Uploaded by

susuela
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Django Tutorial

Django is a back-end server side web framework.

Django is free, open source and written in Python.

Django makes it easier to build web pages using Python.

Learning by Doing
In this tutorial you get a step by step guide on how to install and create a Django project.
You will learn how to create a project where you can add, read, update or delete data.

You will learn how to make HTML Templates and use Django Template Tags to insert data
within a HTML document.

You will learn how to work with QuerySets to extract, filter, and sort data from the database.

You will also learn how to set up a PostgreSQL database and how to deploy your Django
project to the world.

Django Exercises
Exercise:
Insert the missing parts to write a Django variable in a template:

<h1>Hello firstname , how are you?</h1>

Submit Answer »

Django Quiz
Learn by taking a quiz! The quiz will give you a signal of how much you know about Django.

Start Django Quiz

Learning by Examples
In the tutorial we will use examples to better explain the various concepts.

Example
<ul>
{% for x in mymembers %}

<li>{{ [Link] }}</li>

{% endfor %}

</ul>

Run Example »

My Learning
Track your progress with the free "My Learning" program here at W3Schools.

Log in to your account, and start earning points!

This is an optional feature. You can study W3Schools without using My Learning.

Django Introduction
What is Django?
Django is a Python framework that makes it easier to create web sites using Python.

Django takes care of the difficult stuff so that you can concentrate on building your web
applications.

Django emphasizes reusability of components, also referred to as DRY (Don't Repeat


Yourself), and comes with ready-to-use features like login system, database connection and
CRUD operations (Create Read Update Delete).

Django is especially helpful for database driven websites.

How does Django Work?


Django follows the MVT design pattern (Model View Template).

 Model - The data you want to present, usually data from a database.
 View - A request handler that returns the relevant template and content - based on the
request from the user.
 Template - A text file (like an HTML file) containing the layout of the web page, with
logic on how to display the data.

Model
The model provides data from the database.
In Django, the data is delivered as an Object Relational Mapping (ORM), which is a technique
designed to make it easier to work with databases.

The most common way to extract data from a database is SQL. One problem with SQL is that
you have to have a pretty good understanding of the database structure to be able to work
with it.

Django, with ORM, makes it easier to communicate with the database, without having to
write complex SQL statements.

The models are usually located in a file called [Link].

View
A view is a function or method that takes http requests as arguments, imports the relevant
model(s), and finds out what data to send to the template, and returns the final result.

The views are usually located in a file called [Link].

Template
A template is a file where you describe how the result should be represented.

Templates are often .html files, with HTML code describing the layout of a web page, but it
can also be in other file formats to present other results, but we will concentrate on .html
files.

Django uses standard HTML to describe the layout, but uses Django tags to add logic:

<h1>My Homepage</h1>

<p>My name is {{ firstname }}.</p>

The templates of an application is located in a folder named templates.

URLs
Django also provides a way to navigate around the different pages in a website.

When a user requests a URL, Django decides which view it will send it to.

This is done in a file called [Link].

So, What is Going On?


When you have installed Django and created your first Django web application, and the
browser requests the URL, this is basically what happens:

1. Django receives the URL, checks the [Link] file, and calls the view that matches the
URL.
2. The view, located in [Link], checks for relevant models.
3. The models are imported from the [Link] file.
4. The view then sends the data to a specified template in the template folder.
5. The template contains HTML and Django tags, and with the data it returns finished
HTML content back to the browser.

Django can do a lot more than this, but this is basically what you will learn in this tutorial,
and are the basic steps in a simple web application made with Django.

Django History
Django was invented by Lawrence Journal-World in 2003, to meet the short deadlines in the
newspaper and at the same time meeting the demands of experienced web developers.

Initial release to the public was in July 2005.

Latest version of Django is 4.0.3 (March 2022).

Django Getting Started


To install Django, you must have Python installed, and a package manager like PIP.

PIP is included in Python from version 3.4.

Django Requires Python


To check if your system has Python installed, run this command in the command prompt:

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: [Link]

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.

For me, on a windows machine, the result looks like this:

pip 20.2.3 from c:\python39\lib\site-packages\pip (python 3.9)

If you do not have PIP installed, you can download and install it from this
page: [Link]

Virtual Environment
It is suggested to have a dedicated virtual environment for each Django project, and in
the next chapter you will learn how to create a virtual environment, and the install Django in
it.

Django - Create Virtual


Environment
Virtual Environment
It is suggested to have a dedicated virtual environment for each Django project, and 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.

Type the following in the command prompt, remember to navigate to where you want to
create your project:

Windows:

py -m venv myworld

Unix/MacOS:

python -m venv myworld

This will set up a virtual environment, and create a folder named "myworld" with subfolders
and files, like this:

myworld
Include
Lib
Scripts
[Link]

Then you have to activate the environment, by typing this command:

Windows:

myworld\Scripts\[Link]

Unix/MacOS:

source myworld/bin/activate

Once the environment is activated, you will see this result in the command prompt:

Windows:

(myworld) C:\Users\Your Name>

Unix/MacOS:

(myworld) ... $

Note: You must activate the virtual environment every time you open the command prompt
to work on your project.

Install Django
In the next chapter you will finally learn how to install Django!

Install Django
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!

Django is installed using pip, with this command:

Windows:

(myworld) C:\Users\Your Name>py -m pip install Django

Unix/MacOS:

(myworld) ... $ python -m pip install Django

Which will give a result that looks like this (at least on my Windows machine):
Collecting Django
Downloading [Link] (8.0 MB)
|████████████████████████████████| 8.0 MB 2.2 MB/s
Collecting sqlparse>=0.2.2
Using cached [Link] (42 kB)
Collecting asgiref<4,>=3.4.1
Downloading [Link] (22 kB)
Collecting tzdata; sys_platform == "win32"
Downloading [Link] (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\
[Link] -m pip install --upgrade pip' command.

That's it! Now you have installed Django in your new project, running in a virtual
environment!

Windows, Mac, or Unix?


You can run this project on either one. There are some small differences, like when writing
commands in the command prompt, Windows uses py as the first word in the command line,
while Unix and MacOS use python:

Windows:

py --version

Unix/MacOS:

python --version

In the rest of this tutorial, we will be using the Windows command.

Check Django Version


You can check if Django is installed by asking for its version number like this:

(myworld) C:\Users\Your Name>django-admin --version

If Django is installed, you will get a result with the version number:

4.1.2

What's Next?
Now you are ready to create a Django project in a virtual environment on your computer.

In the next chapters of this tutorial we will create a Django project and look at the various
features of Django and hopefully make you a Django developer.

Django Create Project


My First Project
Once you have come up with a suitable name for your Django project, like
mine: my_tennis_club, navigate to where in the file system you want to store the code (in
the virtual environment), I will navigate to the myworld folder, and run this command in the
command prompt:

django-admin startproject my_tennis_club

Django creates a my_tennis_club folder on my computer, with this content:

my_tennis_club
[Link]
my_tennis_club/
__init__.py
[Link]
[Link]
[Link]
[Link]

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.

Run the Django Project


Now that you have a Django project, you can run it, and see what it looks like in a browser.

Navigate to the /my_tennis_club folder and execute this command in the command
prompt:

py [Link] runserver

Which will produce this result:

Watching for file changes with StatReloader


Performing system checks...

System check identified no issues (0 silenced).


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 [Link] 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 [Link]
Quit the server with CTRL-BREAK.

Open a new browser window and type [Link]:8000 in the address bar.

The result:

What's Next?
We have a Django project!

The next step is to make an app in your project.


You cannot have a web page created with Django without an app.

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.

mStart 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.

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.

py [Link] startapp members

Django creates a folder named members in my project, with this content:

my_tennis_club
[Link]
my_tennis_club/
members/
migrations/
__init__.py
__init__.py
[Link]
[Link]
[Link]
[Link]
[Link]

These are all files and folders with a specific meaning. You will learn about most of them
later in this tutorial.

First, take a look at the file called [Link].

This is where we gather the information we need to send back a proper response.
You will learn more about views in the next chapter.

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 [Link] located on your app's folder.

There is a [Link] in your members folder that looks like this:

my_tennis_club/members/[Link]:

from [Link] import render

# Create your views here.

Find it and open it, and replace the content with this:

my_tennis_club/members/[Link]:

from [Link] import render

from [Link] import HttpResponse

def members(request):

return HttpResponse("Hello world!")

Note: The name of the view does not have to be the same as the application.

I call it members because I think it fits well in this context.

This is a simple example on how to send a response back to the browser.

But how can we execute the view? Well, we must call the view via a URL.

You will learn about URLs in the next chapter.

Django URLs
URLs
Create a file named [Link] in the same folder as the [Link] file, and type this code in
it:

my_tennis_club/members/[Link]:

from [Link] import path

from . import views

urlpatterns = [

path('members/', [Link], name='members'),

The [Link] 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 [Link] 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 [Link]:8000/.

Then your file will look like this:

my_tennis_club/my_tennis_club/[Link]:

from [Link] import admin

from [Link] import include, path

urlpatterns = [

path('', include('[Link]')),

path('admin/', [Link]),

If the server is not running, navigate to the /my_tennis_club folder and execute this
command in the command prompt:

py [Link] runserver

In the browser window, type [Link]:8000/members/ in the address bar.


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 [Link].

The file structure should be like this:

my_tennis_club
[Link]
my_tennis_club/
members/
templates/
[Link]
Open the HTML file and insert the following:

my_tennis_club/members/templates/[Link]:

<!DOCTYPE html>

<html>

<body>

<h1>Hello World!</h1>

<p>Welcome to my first Django project!</p>

</body>

</html>

Modify the View


Open the [Link] file and replace the members view with this:

my_tennis_club/members/[Link]:

from [Link] import HttpResponse

from [Link] import loader

def members(request):

template = loader.get_template('[Link]')

return HttpResponse([Link]())

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.

This is done in the [Link] file in the my_tennis_club folder.

Look up the INSTALLED_APPS[] list and add the members app like this:
my_tennis_club/my_tennis_club/[Link]:

INSTALLED_APPS = [

'[Link]',

'[Link]',

'[Link]',

'[Link]',

'[Link]',

'[Link]',

'members'

Then run this command:

py [Link] migrate

Which will produce this output:

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
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

(myworld) C:\Users\Your Name\myworld\my_tennis_club>


Start the server by navigating to the /my_tennis_club folder and execute this command:

py [Link] runserver

In the browser window, type [Link]:8000/members/ in the address bar.

The result should look like this:

Django Models
A Django model is a table in your database.

Django Models
Up until now in this tutorial, 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 prosess.

In Django, data is created in objects, called Models, and is actually tables in a database.
Create Table (Model)
To create a model, navigate to the [Link] file in the /members/ folder.

Open it, and add a Member table by creating a Member class, and describe the table fields in
it:

my_tennis_club/members/[Link]:

from [Link] import models

class Member([Link]):

firstname = [Link](max_length=255)

lastname = [Link](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.

Both firstname and lastname is set up to have a maximum of 255 characters.

SQLite Database
When we created the Django project, we got an empty SQLite database.

It was created in the my_tennis_club root folder, and has the filename db.sqlite3.

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 [Link] file, we must run a command to
actually create the table in the database.

Navigate to the /my_tennis_club/ folder and run this command:

py [Link] makemigrations members

Which will result in this output:

Migrations for 'members':


members\migrations\0001_initial.py
- Create model Member

(myworld) C:\Users\Your Name\myworld\my_tennis_club>


Django creates a file describing the changes and stores the file in the /migrations/ folder:

my_tennis_club/members/migrations/0001_initial.py:

# Generated by Django 4.1.2 on 2022-10-27 11:14

from [Link] import migrations, models

class Migration([Link]):

initial = True

dependencies = [

operations = [

[Link](

name='Member',

fields=[

('id', [Link](auto_created=True,
primary_key=True, serialize=False, verbose_name='ID')),

('firstname', [Link](max_length=255)),

('lastname', [Link](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.

Run the migrate command:

py [Link] migrate

Which will result in this output:

Operations to perform:
Apply all migrations: admin, auth, contenttypes, members, sessions
Running migrations:
Applying members.0001_initial... OK

(myworld) C:\Users\Your Name\myworld\my_tennis_club>

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:

py [Link] sqlmigrate members 0001

Which will result in this output:

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;

Django Insert Data


Add Records
The Members table created in the previous chapter is empty.

We will use the Python interpreter (Python shell) to add some members to it.

To open a Python shell, type this command:

py [Link] shell
Now we are in the shell, the result should be something like this:

Python 3.9.2 (tags/v3.9.2:1a79785, Feb 19 2021, 13:44:55) [MSC v.1928 64 bit


(AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>>

At the bottom, after the three >>> write the following:

>>> from [Link] import Member

Hit [enter] and write this to look at the empty Member table:

>>> [Link]()

This should give you an empty QuerySet object, like this:

<QuerySet []>

A QuerySet is a collection of data from a database.

Read more about QuerySets in the Django QuerySet chapter.

Add a record to the table, by executing these two lines:

>>> member = Member(firstname='Emil', lastname='Refsnes')


>>> [Link]()

Execute this command to see if the Member table got a member:

>>> [Link]().values()

Hopefully, the result will look like this:

<QuerySet [{'id': 1, 'firstname': 'Emil', 'lastname': 'Refsnes'}]>

Add Multiple Records


You can add multiple records by making a list of Member objects, and execute .save() on each
entry:

>>> member1 = Member(firstname='Tobias', lastname='Refsnes')


>>> member2 = Member(firstname='Linus', lastname='Refsnes')
>>> member3 = Member(firstname='Lene', lastname='Refsnes')
>>> member4 = Member(firstname='Stale', lastname='Refsnes')
>>> member5 = Member(firstname='Jane', lastname='Doe')
>>> members_list = [member1, member2, member3, member4, member5]
>>> for x in members_list:
>>> [Link]()

Now there are 6 members in the Member table:

>>> [Link]().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'}]>

Django Update Data


Update Records
To update records that are already in the database, we first have to get the record we want
to update:

>>> from [Link] import Member


>>> x = [Link]()[4]

x will now represent the member at index 4, which is "Stale Refsnes", but to make sure, let
us see if that is correct:

>>> [Link]

This should give you this result:

'Stale'

Now we can change the values of this record:

>>> [Link] = "Stalikken"


>>> [Link]()

Execute this command to see if the Member table got updated:

>>> [Link]().values()

Hopefully, the result will look like this:

<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'},
{'id': 6, 'firstname': 'Jane', 'lastname': 'Doe'}]>
Django Delete Data
Delete Records
To delete a record in a table, start by getting the record you want to delete:

>>> from [Link] import Member


>>> x = [Link]()[5]

x will now represent the member at index 5, which is "Jane Doe", but to make sure, let us see
if that is correct:

>>> [Link]

This should give you this result:

'Jane'

Now we can delete the record:

>>> [Link]()

The result will be:

(1, {'[Link]': 1})

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:

>>> [Link]().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'}]>

Django Update Model


Add Fields in the Model
To add a field to a table after it is created, open the [Link] file, and make your changes:

my_tennis_club/members/[Link]:
from [Link] import models

class Member([Link]):

firstname = [Link](max_length=255)

lastname = [Link](max_length=255)

phone = [Link]()

joined_date = [Link]()

As you can see, we want to add phone and joined_date to our Member Model.

This is a change in the Model's structure, and therefor we have to make a migration to tell
Django that it has to update the database:

py [Link] makemigrations members

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:

py [Link] 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 [Link]
Select an option:

I will select option 2, and open the [Link] file again and allow NULL values for the two
new fields:

my_tennis_club/members/[Link]:

from [Link] import models

class Member([Link]):

firstname = [Link](max_length=255)

lastname = [Link](max_length=255)

phone = [Link](null=True)
joined_date = [Link](null=True)

And make the migration once again:

py [Link] makemigrations members

Which will result in this:

Migrations for 'members':


members\migrations\0002_member_joined_date_member_phone.py
- Add field joined_date to member
- Add field phone to member

Run the migrate command:

py [Link] migrate

Which will result in this output:

Operations to perform:
Apply all migrations: admin, auth, contenttypes, members, sessions
Running migrations:
Applying members.0002_member_joined_date_member_phone... OK

(myworld) C:\Users\Your Name\myworld\my_tennis_club>

Insert Data
We can insert data to the two new fields with the same approach as we did in the Update
Data chapter:

First we enter the Python Shell:

py [Link] shell

Now we are in the shell, the result should be something like this:

Python 3.9.2 (tags/v3.9.2:1a79785, Feb 19 2021, 13:44:55) [MSC v.1928 64 bit


(AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>>

At the bottom, after the three >>> write the following (and hit [enter] for each line):

>>> from [Link] import Member


>>> x = [Link]()[0]
>>> [Link] = 5551234
>>> x.joined_date = '2022-01-05'
>>> [Link]()

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.

Execute this command to see if the Member table got updated:

>>> [Link]().values()

The result should look like this:

<QuerySet [
{'id': 1, 'firstname': 'Emil', 'lastname': 'Refsnes', 'phone': 5551234,
'joined_date': [Link](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},
{'id': 4, 'firstname': 'Lene', 'lastname': 'Refsnes', 'phone': None,
'joined_date': None},
{'id': 5, 'firstname': 'Stalikken', 'lastname': 'Refsnes', 'phone': None,
'joined_date

Django Prepare Template


Create Template
After creating Models, with the fields and data we want in them, it is time to display the data
in a web page.

Start by creating an HTML file named all_members.html and place it in


the /templates/ folder:

my_tennis_club/members/templates/all_members.html:

<!DOCTYPE html>

<html>

<body>

<h1>Members</h1>

<ul>
{% for x in mymembers %}

<li>{{ [Link] }} {{ [Link] }}</li>

{% endfor %}

</ul>

</body>

</html>

Do you see the {% %} brackets inside the HTML document?

They are Django Tags, telling Django to perform some programming logic inside these
brackets.

You will learn more about Django Tags in our Django Tags chapter.

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/[Link]:

from [Link] import HttpResponse

from [Link] import loader

from .models import Member

def members(request):

mymembers = [Link]().values()

template = loader.get_template('all_members.html')

context = {

'mymembers': mymembers,

return HttpResponse([Link](context, request))


Run Example »

The members view does the following:

 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.

The Result
We have created an example so that you can see the result:

Run Example »

If you have followed all the steps on your own computer, you can see the result in your own
browser:

Start the server by navigating to the /my_tennis_club/ folder and execute this command:

py [Link] runserver

In the browser window, type [Link]:8000/members/ in the address bar.

Django Add Link to Details


Details Template
The next step in our web page will be to add a Details page, where we can list more details
about a specific member.

Start by creating a new template called [Link]:

my_tennis_club/members/templates/[Link]:

<!DOCTYPE html>

<html>

<body>
<h1>{{ [Link] }} {{ [Link] }}</h1>

<p>Phone: {{ [Link] }}</p>

<p>Member since: {{ mymember.joined_date }}</p>

<p>Back to <a href="/members">Members</a></p>

</body>

</html>

Add Link in all-members Template


The list in all_members.html should be clickable, and take you to the details page with the
ID of the member you clicked on:

my_tennis_club/members/templates/all_members.html:

<!DOCTYPE html>

<html>

<body>

<h1>Members</h1>

<ul>

{% for x in mymembers %}

<li><a href="details/{{ [Link] }}">{{ [Link] }} {{ [Link]


}}</a></li>

{% endfor %}

</ul>

</body>
</html>

Create new View


Then create a new view in the [Link] file, that will deal with incoming requests to
the /details/ url:

my_tennis_club/members/[Link]:

from [Link] import HttpResponse

from [Link] import loader

from .models import Member

def members(request):

mymembers = [Link]().values()

template = loader.get_template('all_members.html')

context = {

'mymembers': mymembers,

return HttpResponse([Link](context, request))

def details(request, id):

mymember = [Link](id=id)

template = loader.get_template('[Link]')

context = {

'mymember': mymember,

return HttpResponse([Link](context, request))


The details view does the following:

 Gets the id as an argument.


 Uses the id to locate the correct record in the Member table.
 loads the [Link] template.
 Creates an object containing the member.
 Sends the object to the template.
 Outputs the HTML that is rendered by the template.

Add URLs
Now we need to make sure that the /details/ url points to the correct view, with id as a
parameter.

Open the [Link] file and add the details view to the urlpatterns list:

my_tennis_club/members/[Link]:

from [Link] import path

from . import views

urlpatterns = [

path('members/', [Link], name='members'),

path('members/details/<int:id>', [Link], name='details'),

Run Example »

If you have followed all the steps on your own computer, you can see the result in your own
browser: [Link]:8000/members/.

If the server is down, you have to start it again with the runserver command:

py [Link] runserver
Django Add Master Template
The extends Tag
In the previous pages we created two templates, one for listing all members, and one for
details about a member.

The templates have a set of HTML code that are the same for both templates.

Django provides a way of making a "parent template" that you can include in all pages to for
the stuff that are the same in all pages.

Start by creating a template called [Link], with all the necessary HTML elements:

Master
my_tennis_club/members/templates/[Link]:

<!DOCTYPE html>

<html>

<head>

<title>{% block title %}{% endblock %}</title>

</head>

<body>

{% block content %}

{% endblock %}

</body>

</html>

Do you see Django block Tag inside the <title> element, and the <body> element?

They are placeholders, telling Django to replace this block with content from other sources.

Modify Templates
Now the two templates (all_members.html and [Link]) can use
this [Link] template.

This is done by including the master template with the {% extends %} tag, and inserting
a title block and a content block:

Members
my_tennis_club/members/templates/all_members.html:

{% extends "[Link]" %}

{% block title %}

My Tennis Club - List of all members

{% endblock %}

{% block content %}

<h1>Members</h1>

<ul>

{% for x in mymembers %}

<li><a href="details/{{ [Link] }}">{{ [Link] }} {{ [Link]


}}</a></li>

{% endfor %}

</ul>

{% endblock %}

Run Example »

Details
my_tennis_club/members/templates/[Link]:

{% extends "[Link]" %}

{% block title %}
Details about {{ [Link] }} {{ [Link] }}

{% endblock %}

{% block content %}

<h1>{{ [Link] }} {{ [Link] }}</h1>

<p>Phone {{ [Link] }}</p>

<p>Member since: {{ mymember.joined_date }}</p>

<p>Back to <a href="/members">Members</a></p>

{% endblock %}

Run Example »

If you have followed all the steps on your own computer, you can see the result in your own
browser: [Link]:8000/members/.

If the server is down, you have to start it again with the runserver command:

py [Link] runserver

Django Add Main Index Page


Main Index Page
Our project needs a main page.

The main page will be the landing page when someone visits the root folder of the project.

Now, you get an error when visiting the root folder of your project:

[Link]:8000/.

Start by creating a template called [Link]:


Main
my_tennis_club/members/templates/[Link]:

{% extends "[Link]" %}

{% block title %}

My Tennis Club

{% endblock %}

{% block content %}

<h1>My Tennis Club</h1>

<h3>Members</h3>

<p>Check out all our <a href="members/">members</a></p>

{% endblock %}

Create new View


Then create a new view called main, that will deal with incoming requests to root of the
project:

my_tennis_club/members/[Link]:

from [Link] import HttpResponse

from [Link] import loader

from .models import Member

def members(request):
mymembers = [Link]().values()

template = loader.get_template('all_members.html')

context = {

'mymembers': mymembers,

return HttpResponse([Link](context, request))

def details(request, id):

mymember = [Link](id=id)

template = loader.get_template('[Link]')

context = {

'mymember': mymember,

return HttpResponse([Link](context, request))

def main(request):

template = loader.get_template('[Link]')

return HttpResponse([Link]())

The main view does the following:

 loads the [Link] template.


 Outputs the HTML that is rendered by the template.

Add URL
Now we need to make sure that the root url points to the correct view.
Open the [Link] file and add the main view to the urlpatterns list:

my_tennis_club/members/[Link]:

from [Link] import path

from . import views

urlpatterns = [

path('', [Link], name='main'),

path('members/', [Link], name='members'),

path('members/details/<int:id>', [Link], name='details'),

Run Example »

Add Link Back to Main


The members page is missing a link back to the main page, so let us add that in
the all_members.html template, in the content block:

Example
my_tennis_club/members/templates/all_members.html:

{% extends "[Link]" %}

{% block title %}

My Tennis Club - List of all members

{% endblock %}

{% block content %}
<p><a href="/">HOME</a></p>

<h1>Members</h1>

<ul>

{% for x in mymembers %}

<li><a href="details/{{ [Link] }}">{{ [Link] }} {{ [Link]


}}</a></li>

{% endfor %}

</ul>

{% endblock %}

Run Example »

If you have followed all the steps on your own computer, you can see the result in your own
browser: [Link]:8000/.

If the server is down, you have to start it again with the runserver command:

py [Link] runserver

Django 404 (page not found)


Page Not Found
If you try to access a page that does not exist (a 404 error), Django directs you to a built-in
view that handles 404 errors.

You will learn how to customize this 404 view later in this chapter, but first, just try to
request a page that does not exist.

In the browser window, type [Link]:8000/masfdfg/ in the address bar.

You will get one of two results:

1:
2:
If you got the first result, you got directed to the built-in Django 404 template.

If you got the second result, then DEBUG is set to True in your settings, and you must set it
to False to get directed to the 404 template.

This is done in the [Link] file, which is located in the project folder, in our case
the my_tennis_club folder, where you also have to specify the host name from where your
project runs from:

Example
Set the debug property to False, and allow the project to run from your local host:

my_tennis_club/my_tennis_club/[Link]:

# SECURITY WARNING: don't run with debug turned on in production!

DEBUG = False
ALLOWED_HOSTS = ['*']

Important: When DEBUG = False, Django requires you to specify the hosts you will allow
this Django project to run from.

In production, this should be replaced with a proper domain name:

ALLOWED_HOSTS = ['[Link]']

In the browser window, type [Link]:8000/masfdfg/ in the address bar, and you will
get the built-in 404 template:

Customize the 404 Template


Django will look for a file named [Link] in the templates folder, and display it when
there is a 404 error.

If no such file exists, Django shows the "Not Found" that you saw in the example above.

To customize this message, all you have to do is to create a file in the templates folder and
name it [Link], and fill it with write whatever you want:

my_tennis_club/members/templates/[Link]:

<!DOCTYPE html>
<html>
<title>Wrong address</title>
<body>

<h1>Ooops!</h1>

<h2>I cannot find the file you requested!</h2>

</body>
</html>

In the browser window, type [Link]:8000/masfdfg/ in the address bar, and you will
get the customized 404 template:
Django Add Test View
Test View
When testing different aspects of Django, it can be a good idea to have somewhere to test
code without destroying the main project.

This is optional off course, but if you like to follow all steps in this tutorial, you should add a
test view that is exactly like the one we create below.

Then you can follow the examples and try them out on your own computer.

Add View
Start by adding a view called "testing" in the [Link] file:

my_tennis_club/members/[Link]:

from [Link] import HttpResponse


from [Link] import loader

from .models import Member

def members(request):

mymembers = [Link]().values()

template = loader.get_template('all_members.html')

context = {

'mymembers': mymembers,

return HttpResponse([Link](context, request))

def details(request, id):

mymember = [Link](id=id)

template = loader.get_template('[Link]')

context = {

'mymember': mymember,

return HttpResponse([Link](context, request))

def main(request):

template = loader.get_template('[Link]')

return HttpResponse([Link]())

def testing(request):

template = loader.get_template('[Link]')

context = {

'fruits': ['Apple', 'Banana', 'Cherry'],

}
return HttpResponse([Link](context, request))

URLs
We have to make sure that incoming urls to /testing/ will be redirected to the testing view.

This is done in the [Link] file in the members folder:

my_tennis_club/members/[Link]:

from [Link] import path

from . import views

urlpatterns = [

path('', [Link], name='main'),

path('members/', [Link], name='members'),

path('members/details/<int:id>', [Link], name='details'),

path('testing/', [Link], name='testing'),

Test Template
We also need a template where we can play around with HTML and Django code.

You might noticed that there was a reference to a template in the testing view?

Create a template called "[Link]" in the templates folder:

my_tennis_club
[Link]
my_tennis_club/
members/
templates/
[Link]
all_members.html
[Link]
[Link]
[Link]
[Link]
[Link]
Open the [Link] file and insert the following:

my_tennis_club/members/templates/[Link]:

<!DOCTYPE html>

<html>

<body>

{% for x in fruits %}

<h1>{{ x }}</h1>

{% endfor %}

<p>In [Link] you can see what the fruits variable looks like.</p>

</body>

</html>

Run Example »

If the server is not running, navigate to the /my_tennis_club folder and execute this
command in the command prompt:

py [Link] runserver

In the browser window, type [Link]:8000/testing/ in the address bar.

The result should be like this:


Django Admin
Django Admin
Django Admin is a really great tool in Django, it is actually a CRUD* user interface of all your
models!

*CRUD stands for Create Read Update Delete.

It is free and comes ready-to-use with Django:


Getting Started
To enter the admin user interface, start the server by navigating to the /myworld folder and
execute this command:

py [Link] runserver

In the browser window, type [Link]:8000/admin/ in the address bar.

The result should look like this:


The reason why this URL goes to the Django admin log in page can be found in
the [Link] file of your project:

my_tennis_club/my_tennis_club/[Link]:

from [Link] import admin

from [Link] import include, path

urlpatterns = [

path('', include('[Link]')),

path('admin/', [Link]),

The urlpatterns[] list takes requests going to admin/ and sends them
to [Link], which is part of a built-in application that comes with Django, and
contains a lot of functionality and user interfaces, one of them being the log-in user
interface.

Django Admin - Create User


Create User
To be able to log into the admin application, we need to create a user.

This is done by typing this command in the command view:

py [Link] createsuperuser

Which will give this prompt:

Username:

Here you must enter: username, e-mail address, (you can just pick a fake e-mail address),
and password:

Username: johndoe
Email address: johndoe@[Link]
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]:

My password did not meet the criteria, but this is a test environment, and I choose to create
user anyway, by enter y:

Bypass password validation and create user anyway? [y/N]: y

If you press [Enter], you should have successfully created a user:

Superuser created successfully.

Now start the server again:

py [Link] runserver

In the browser window, type [Link]:8000/admin/ in the address bar.

And fill in the form with the correct username and password:
Which should result in this user interface:
Here you can create, read, update, and delete groups and users, but where is the Members
model?

Missing Model
The Members model is missing, as it should be, you have to tell Django which models that
should be visible in the admin interface.

You will learn how to include the Members model in the next chapter.

Django Admin - Include Member


Include Member in the Admin Interface
To include the Member model in the admin interface, we have to tell Django that this model
should be visible in the admin interface.

This is done in a file called [Link], and is located in your app's folder, which in our case is
the members folder.

Open it, and it should look like this:


my_tennis_club/members/[Link]:

from [Link] import admin

# Register your models here.

Insert a couple of lines here to make the Member model visible in the admin page:

my_tennis_club/members/[Link]:

from [Link] import admin

from .models import Member

# Register your models here.

[Link](Member)

Now go back to the browser and you should get this result:

Click Members and see the five records we inserted earlier in this tutorial:
Change Display
In the list in the screenshot above, we see "Member object (1)", "Member object (2)" etc.
which might not be the data you wanted to be displayed in the list.

It would be better to display "firstname" and "lastname" instead.

This can easily be done by changing some settings in the [Link] and/or
the [Link] files. You will learn more about this in the next chapter.
Django Admin - Set Fields to
Display
Make the List Display More Reader-
Friendly
When you display a Model as a list, Django displays each record as the string representation
of the record object, which in our case is "Member object (1)", "Member object(2)" etc.:
To change this to a more reader-friendly format, we have two choices:

1. Change the string representation function, __str__() of the Member Model


2. Set the list_details property of the Member Model

Change the String Representation Function


To change the string representation, we have to define the __str__() function of the
Member Model in [Link], like this:

my_tennis_club/members/[Link]:

from [Link] import models

class Member([Link]):

firstname = [Link](max_length=255)

lastname = [Link](max_length=255)

phone = [Link](null=True)

joined_date = [Link](null=True)

def __str__(self):

return f"{[Link]} {[Link]}"

Which gives us this result:


Defining our own __str__() function is not a Django feature, it is how to change the string
representation of objects in Python. Read more about Python objects in our Python object
tutorial.

Set list_display
We can control the fields to display by specifying them in in a list_display property in
the [Link] file.

First create a MemberAdmin() class and specify the list_display tuple, like this:

my_tennis_club/members/[Link]:
from [Link] import admin

from .models import Member

# Register your models here.

class MemberAdmin([Link]):

list_display = ("firstname", "lastname", "joined_date",)

[Link](Member, MemberAdmin)

Remember to add the MemberAdmin as an argumet in the [Link](Member,


MemberAdmin).

Now go back to the browser and you should get this result:
Django Admin - Update Members
Update Members
Now we are able to create, update, and delete members in our database, and we start by
giving them all a date for when they became members.

Click the first member, Stalikken, to open the record for editing, and give him
a joined_date:
While we are in here, let us give him a phone number as well:
Click "SAVE" and go back to the list of all members:
Repeat these steps and give all members a date and a phone number, and end up with a list
like this:
Django Admin - Add Members
Add Members
To add a new member, click on the "ADD MEMBERS" button in the top right corner:
You will get an empty form where you can fill in the members fields:
Fill in the fields and click "SAVE":
Now the Members Model have 6 members:
Django Admin - Delete Members
Delete Members
To delete a new member, you can either select a member and choose the action "Delete
selected members" like this:

Run Demo
Or you can open a member for editing, and click the red DELETE button at the bottom, like
this:

Run Demo
Django Syntax

Django Template Variables


Template Variables
In Django templates, you can render variables by putting them inside {{ }} brackets:

Example
templates/[Link]:

<h1>Hello {{ firstname }}, how are you?</h1>

Run Example »

Create Variable in View


The variable firstname in the example above was sent to the template via a view:

[Link]:

from [Link] import HttpResponse

from [Link] import loader

def testing(request):

template = loader.get_template('[Link]')

context = {

'firstname': 'Linus',

return HttpResponse([Link](context, request))

Run Example »

As you can see in the view above, we create an object named context and fill it with data,
and send it as the first parameter in the [Link]() function.

Create Variables in Template


You can also create variables directly in the template, by using the {% with %} template
tag:

Example
templates/[Link]:

{% with firstname="Tobias" %}

<h1>Hello {{ firstname }}, how are you?</h1>

Run Example »

You will learn more about template tags in the next chapter.

Data From a Model


The example above showed a easy approach on how to create and use variables in a
template.

Normally, most of the external data you want to use in a template, comes from a model.

We have created a model in the previous chapters, called Member, which we will use in many
examples in the next chapters of this tutorial.

To get data from the Member model, we will have to import it in the [Link] file, and
extract data from it in the view:

members/[Link]:

from [Link] import HttpResponse, HttpResponseRedirect

from [Link] import loader

from .models import Member

def testing(request):

mymembers = [Link]().values()

template = loader.get_template('[Link]')

context = {

'mymembers': mymembers,

return HttpResponse([Link](context, request))

Now we can use the data in the template:

templates/[Link]:

<ul>

{% for x in mymembers %}

<li>{{ [Link] }}</li>

{% endfor %}

</ul>

Run Example »

We use the Django template tag {% for %} to loop through the members.

You will learn more about template tags in the next chapter.

You might also like