Django Models
Django Models
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:
Submit Answer »
Django Quiz
Learn by taking a quiz! The quiz will give you a signal of how much you know about Django.
Learning by Examples
In the tutorial we will use examples to better explain the various concepts.
Example
<ul>
{% for x in mymembers %}
{% endfor %}
</ul>
Run Example »
My Learning
Track your progress with the free "My Learning" program here at W3Schools.
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.
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.
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.
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>
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.
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.
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.
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.
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:
This will set up a virtual environment, and create a folder named "myworld" with subfolders
and files, like this:
myworld
Include
Lib
Scripts
[Link]
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:
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!
Windows:
Unix/MacOS:
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:
py --version
Unix/MacOS:
python --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.
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.
Navigate to the /my_tennis_club folder and execute this command in the command
prompt:
py [Link] runserver
Open a new browser window and type [Link]:8000 in the address bar.
The result:
What's Next?
We have a Django project!
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.
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.
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.
my_tennis_club/members/[Link]:
Find it and open it, and replace the content with this:
my_tennis_club/members/[Link]:
def members(request):
Note: The name of the view does not have to be the same as the application.
But how can we execute the view? Well, we must call the view via a URL.
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]:
urlpatterns = [
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/.
my_tennis_club/my_tennis_club/[Link]:
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
Create a templates folder inside the members folder, and create a HTML file
named [Link].
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>
</body>
</html>
my_tennis_club/members/[Link]:
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.
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'
py [Link] 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
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
py [Link] runserver
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]:
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.
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.
my_tennis_club/members/migrations/0001_initial.py:
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.
py [Link] migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, members, sessions
Running migrations:
Applying members.0001_initial... OK
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 [Link] shell
Now we are in the shell, the result should be something like this:
Hit [enter] and write this to look at the empty Member table:
>>> [Link]()
<QuerySet []>
>>> [Link]().values()
>>> [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'}]>
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]
'Stale'
>>> [Link]().values()
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]
'Jane'
>>> [Link]()
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'}]>
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:
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:
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]:
class Member([Link]):
firstname = [Link](max_length=255)
lastname = [Link](max_length=255)
phone = [Link](null=True)
joined_date = [Link](null=True)
py [Link] migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, members, sessions
Running migrations:
Applying members.0002_member_joined_date_member_phone... OK
Insert Data
We can insert data to the two new fields with the same approach as we did in the Update
Data chapter:
py [Link] 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.
>>> [Link]().values()
<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
my_tennis_club/members/templates/all_members.html:
<!DOCTYPE html>
<html>
<body>
<h1>Members</h1>
<ul>
{% for x in mymembers %}
{% endfor %}
</ul>
</body>
</html>
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]:
def members(request):
mymembers = [Link]().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.
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
my_tennis_club/members/templates/[Link]:
<!DOCTYPE html>
<html>
<body>
<h1>{{ [Link] }} {{ [Link] }}</h1>
</body>
</html>
my_tennis_club/members/templates/all_members.html:
<!DOCTYPE html>
<html>
<body>
<h1>Members</h1>
<ul>
{% for x in mymembers %}
{% endfor %}
</ul>
</body>
</html>
my_tennis_club/members/[Link]:
def members(request):
mymembers = [Link]().values()
template = loader.get_template('all_members.html')
context = {
'mymembers': mymembers,
mymember = [Link](id=id)
template = loader.get_template('[Link]')
context = {
'mymember': mymember,
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]:
urlpatterns = [
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>
</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 %}
{% endblock %}
{% block content %}
<h1>Members</h1>
<ul>
{% for x in mymembers %}
{% endfor %}
</ul>
{% endblock %}
Run Example »
Details
my_tennis_club/members/templates/[Link]:
{% extends "[Link]" %}
{% block title %}
Details about {{ [Link] }} {{ [Link] }}
{% endblock %}
{% block content %}
{% 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
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/.
{% extends "[Link]" %}
{% block title %}
My Tennis Club
{% endblock %}
{% block content %}
<h3>Members</h3>
{% endblock %}
my_tennis_club/members/[Link]:
def members(request):
mymembers = [Link]().values()
template = loader.get_template('all_members.html')
context = {
'mymembers': mymembers,
mymember = [Link](id=id)
template = loader.get_template('[Link]')
context = {
'mymember': mymember,
def main(request):
template = loader.get_template('[Link]')
return HttpResponse([Link]())
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]:
urlpatterns = [
Run Example »
Example
my_tennis_club/members/templates/all_members.html:
{% extends "[Link]" %}
{% block title %}
{% endblock %}
{% block content %}
<p><a href="/">HOME</a></p>
<h1>Members</h1>
<ul>
{% for x in mymembers %}
{% 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
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.
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]:
DEBUG = False
ALLOWED_HOSTS = ['*']
Important: When DEBUG = False, Django requires you to specify the hosts you will allow
this Django project to run from.
ALLOWED_HOSTS = ['[Link]']
In the browser window, type [Link]:8000/masfdfg/ in the address bar, and you will
get the built-in 404 template:
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>
</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]:
def members(request):
mymembers = [Link]().values()
template = loader.get_template('all_members.html')
context = {
'mymembers': mymembers,
mymember = [Link](id=id)
template = loader.get_template('[Link]')
context = {
'mymember': mymember,
def main(request):
template = loader.get_template('[Link]')
return HttpResponse([Link]())
def testing(request):
template = loader.get_template('[Link]')
context = {
}
return HttpResponse([Link](context, request))
URLs
We have to make sure that incoming urls to /testing/ will be redirected to the testing view.
my_tennis_club/members/[Link]:
urlpatterns = [
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?
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
py [Link] runserver
my_tennis_club/my_tennis_club/[Link]:
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.
py [Link] createsuperuser
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:
py [Link] runserver
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.
This is done in a file called [Link], and is located in your app's folder, which in our case is
the members folder.
Insert a couple of lines here to make the Member model visible in the admin page:
my_tennis_club/members/[Link]:
[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.
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:
my_tennis_club/members/[Link]:
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):
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
class MemberAdmin([Link]):
[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
Example
templates/[Link]:
Run Example »
[Link]:
def testing(request):
template = loader.get_template('[Link]')
context = {
'firstname': 'Linus',
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.
Example
templates/[Link]:
{% with firstname="Tobias" %}
Run Example »
You will learn more about template tags in the next chapter.
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]:
def testing(request):
mymembers = [Link]().values()
template = loader.get_template('[Link]')
context = {
'mymembers': mymembers,
templates/[Link]:
<ul>
{% for x in mymembers %}
{% 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.