ArmenianChinese (Traditional)EnglishGermanRussian
Python Modules / Django Tutorial -

Python Modules / Django Tutorial

Django Tutorial

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.

Start learning Django now ❯

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 model where you can create, 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.


Learning by Examples

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

Example

<ul>
  {% for x in mymembers %}
    <li>{{ x.firstname }}</li>
  {% endfor %}
</ul>
Run Example »

Learning by References

You will also find references over the most common Django features:

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

You will learn how to install Django in the next chapter.


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 models.py.


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 views.py.


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 provide 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 urls.py.


So, What is Going On?

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

  1. Django receives the URL, checks the urls.py file, and calls the view that matches the URL.
  2. The view, located in views.py, checks for relevant models.
  3. The models are imported from the modals.py 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: 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.

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: https://pypi.org/project/pip/


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.

With venv, you can create a virtual environment by typing this in the command prompt, remember to navigate to where you want to create your project:

Windows:

py -m venv myproject

Unix/MacOS:

python -m venv myproject

This will set up a virtual environment, and create a folder named “myproject” with subfolders and files, like this:

myproject
  Include
  Lib
  Scripts
  pyvenv.cfg

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

Windows:

myproject\Scripts\activate.bat

Unix/MacOS:

source myproject/bin/activate

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

Windows:

(myproject) C:\Users\Your Name>

Unix/MacOS:

(myproject) … $

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


Install Django

Finally, we can install Django.

Remember to install Django while you are in the virtual environment!

Django is installed using pip, with this command:

Windows:

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

Unix/MacOS:

(myproject) … $ python -m pip install Django

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.0.4 is available.
You should consider upgrading via the ‘C:\Users\Your Name\myproject\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, 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:

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

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

4.0.3

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: myworld, navigate to where in the file system you want to store the code (in the virtual environment), and run this command in the command prompt:

django-admin startproject myworld

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

myworld
    manage.py
    myworld/
        __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.


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 /myworld folder and execute this command in the command prompt:

py manage.py 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 manage.py migrate’ to apply them.
December 02, 2021 – 13:14:51
Django version 3.2.9, using settings ‘myworld.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:

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, and run the command below.

If the server is still running, and you are not able to write commands, press [CTRL] [BREAK] to stop the server and you should be back in the virtual environment.

py manage.py startapp members

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

myworld
    manage.py
    myworld/
    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.

First, take a look at the file called views.py.

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 views.py located on your app’s folder.

There is a views.py in your members folder that looks like this:

members/views.py:

from django.shortcuts import render

# Create your views here.

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

members/views.py:

from django.shortcuts import render
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello world!")

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.


URLs

Create a file named urls.py in the same folder as the views.py file, and type this code in it:

members/urls.py:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
]

The urls.py file you just created is specific for the members application. We have to do some routing in the root directory myworld as well. This may seem complicated, but for now, just follow the instructions below.

There is a file called urls.py on the myworld 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/members/.

Then your file will look like this:

myworld/urls.py:

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path(‘members/’, include(‘members.urls’)),
    path(‘admin/’, admin.site.urls),
]

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

py manage.py runserver

In the browser window, type 127.0.0.1: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 myfirst.html.

The file structure should be something like this:

myworld
    manage.py
    myworld/
    members/
        templates/
            myfirst.html

Open the HTML file and insert the following:

members/templates/myfirst.html:

<!DOCTYPE html>
<html>
<body>

<h1>Hello World!</h1>
<p>Welcome to my first Django project!</p>

</body>
</html>

Modify the View

Open the views.py file and replace the index view with this:

members/views.py:

from django.http import HttpResponse
from django.template import loader

def index(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.

This is done in the settings.py file in the myworld folder.

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

myworld/settings.py:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'members.apps.MembersConfig'
]

Then run this command:

py manage.py 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

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

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

py manage.py runserver

In the browser window, type 127.0.0.1:8000/members/ in the address bar.

The result should look like this:

Django Models

A Django model is a table in your database.


SQLite Database

When we created the Django project, we got an empty SQLite database. It was created in the myworld root folder.

We will use this database in this tutorial.


Create Table (Model)

To create a new table, we must create a new model.

In the /members/ folder, open the models.py file. It is almost empty by default, with only an import statement and a comment:

members/models.py:

from django.db import models

# Create your models here.

To add a Members table in our database, start by creating a Members class, and describe the table fields in it:

members/models.py:

from django.db import models

class Members(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 members’ last name.

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

Then navigate to the /myworld/ folder and run this command:

py manage.py makemigrations members

Which will result in this output:

Migrations for ‘members’:
  members\migrations\0001_initial.py
    – Create model Members

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

Django creates a file with any new changes and stores the file in the /migrations/ folder.

Next time you run py manage.py migrate 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 manage.py 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

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

The SQL statement created from the model is:

CREATE TABLE "members_members" (
"id" INT NOT NULL PRIMARY KEY AUTOINCREMENT,
"firstname" varchar(255) NOT NULL,
"lastname" varchar(255) NOT NULL);

Now you have a Members table in you database!

Django Add Members

Add Records

The Members table is empty, we should add some members to it.

In the next chapters you will learn how to make a user interface that will take care of CRUD operations (Create, Read, Update, Delete), but for now, let’s write Python code directly in the Python interpreter (Python shell) and add some members in our database, without the user interface.

To open a Python shell, type this command:

py manage.py 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 members.models import Members

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

>>> Members.objects.all()

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 = Members(firstname=’Emil’, lastname=’Refsnes’)
>>> member.save()

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

>>> Members.objects.all().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 Members obejcts, and execute .save() on each entry:

>>> member1 = Members(firstname=’Tobias’, lastname=’Refsnes’)
>>> member2 = Members(firstname=’Linus’, lastname=’Refsnes’)
>>> member3 = Members(firstname=’Lene’, lastname=’Refsnes’)
>>> member4 = Members(firstname=’Stale’, lastname=’Refsnes’)
>>> members_list = [member1, member2, member3, member4]
>>> for x in members_list:
>>>   x.save()

Now there are 5 members in the Members table:

>>> Members.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’}]>

View in Browser

We want to see the result in a web page, not in a Python shell environment.

To see the result in a web page, we can create a view for this particular task.

In the members app, open the views.py file, if you have followed the previous chapters of this tutorial, it should look like this:

members/views.py:

from django.http import HttpResponse
from django.template import loader

def index(request):
  template = loader.get_template('myfirst.html')
  HttpResponse(template.render())

Change the content in the views.py file to look like this instead:

members/views.py:

from django.http import HttpResponse
from django.template import loader
from .models import Members

def index(request):
  mymembers = Members.objects.all().values()
  output = ""
  for x in mymembers:
    output += x["firstname"]
  return HttpResponse(output)

As you can see in line 3, the Members model is imported, and the index view does the following:

  • makes a mymembers object with all the values of the Members model.
  • Loops through all items in the mymembers object to build a string with all the firstname values.
  • Returns the string as output to the browser.

See the result in your browser. If you are still in the Python shell, write this command to exit the shell:

>>> quit()

Navigate to the /myworld/ folder and type this to start the server:

py manage.py runserver

In the browser window, type 127.0.0.1:8000/members/ in the address bar.

The result:

 

Adding Template

Adding a Template to the Application

In the previous chapter, we managed to display the content of a database table in a web page:

To add some HTML around the values, we will create a template for the application.

All templates must be located in the templates folder off your app, if you have not already created a templates folder, do it now.

In the templates folder, create a file named index.html, with the following content:

members/templates/index.html:

<h1>Members</h1>

<table border="1">
{% for x in mymembers %}
<tr>
<td>{{ x.id }}</td>
<td>{{ x.firstname }}</td>
<td>{{ x.lastname }}</td>
</tr>
{% endfor %}
</table>

Did you notice the {%  %} and {{  }} parts? They are called template tags.

Template tags allows you to perform logic and render variables in your templates, you will learn more about template tags later.


Modify the View

Change the index view to include the template:

members/views.py:

from django.http import HttpResponse
from django.template import loader
from .models import Members

def index(request):
  mymembers = Members.objects.all().values()
  template = loader.get_template('index.html')
  context = {
    'mymembers': mymembers,
  }
  return HttpResponse(template.render(context, request))

The index view does the following:

  • Creates a mymembers object with all the values of the Members model.
  • Loads a the index.html template.
  • Creates an object containing the mymember object.
  • Sends the object to the template.
  • Outputs the HTML that is rendered by the template.

In the browser window, type 127.0.0.1:8000/members/ in the address bar.

The result:

Django Add Record

So far we have created a Members table in our database, and we have inserted five records by writing code in the Python shell.

We have also made a template that allows us to display the content of the table in a web page.

Now we want to be able to create new members from a web page.


Template

Start by adding a link in the members template:

members/templates/index.html:

<h1>Members</h1>

<table border="1">
{% for x in mymembers %}
<tr>
<td>{{ x.id }}</td>
<td>{{ x.firstname }}</td>
<td>{{ x.lastname }}</td>
</tr>
{% endfor %}
</table>

<p>
<a href="add/">Add member</a>
</p>

The result will look like this:


New Template

Add a new template in the templates folder, named add.html:

members/templates/add.html:

<h1>Add member</h1>

<form action="addrecord/" method="post">
{% csrf_token %}
First Name:<br>
<input name="first">
<br><br>
Last Name:<br>
<input name="last">
<br><br>
<input type="submit" value="Submit">
</form>

The template contains an empty HTML form with two input fields and a submit button.

Note: Django requires this line in the form:
{% csrf_token %}
to handle Cross Site Request Forgeries in forms where the method is POST.


View

Next, add a view in the members/views.py file, name the new view add:

members/views.py:

from django.http import HttpResponse
from django.template import loader
from .models import Members

def index(request):
  mymembers = Members.objects.all().values()
  template = loader.get_template('index.html')
  context = {
    'mymembers': mymembers,
  }
  return HttpResponse(template.render(context, request))
  
def add(request):
  template = loader.get_template('add.html')
  return HttpResponse(template.render({}, request))

URLs

Add a path() function in the members/urls.py file, that points the url 127.0.0.1:8000/members/add/ to the right location:

members/urls.py:

from django.urls import path
from . import views

urlpatterns = [
  path('', views.index, name='index'),
  path('add/', views.add, name='add'),
]

In the browser, click the “Add member” link and the result should look like this:


More URLs

Did you notice the action attribute in the HTML form? The action attribute specifies where to send the form data, in this case the form data will be sent to addrecord/, so we must add a path() function in the members/urls.py file that points to the right view:

members/urls.py:

from django.urls import path
from . import views

urlpatterns = [
  path('', views.index, name='index'),
  path('add/', views.add, name='add'),
  path('add/addrecord/', views.addrecord, name='addrecord'),
]

Code for Adding Records

So far we have made the user interface, and we point the URL to the view called addrecord, but we have not made the view yet.

Make sure you add the addrecord view in the in the members/views.py file:

members/views.py:

from django.http import HttpResponse, HttpResponseRedirect
from django.template import loader
from django.urls import reverse
from .models import Members

def index(request):
  mymembers = Members.objects.all().values()
  template = loader.get_template('index.html')
  context = {
    'mymembers': mymembers,
  }
  return HttpResponse(template.render(context, request))
  
def add(request):
  template = loader.get_template('add.html')
  return HttpResponse(template.render({}, request))
  
def addrecord(request):
  x = request.POST['first']
  y = request.POST['last']
  member = Members(firstname=x, lastname=y)
  member.save()
  return HttpResponseRedirect(reverse('index'))

Changes that are made in the views.py file:

Line 1: import HttpResponseRedirect
Line 3: import revers

The addrecord view does the following:

  • Gets the first name and last name with the request.POST statement.
  • Adds a new record in the members table.
  • Redirects the user back to the index view.

Try to add a new record and see how it works:

If you press the submit button, the members table should have been updated:

Django Delete

Deleting Records

To delete a record we do not need a new template, but we need to make some changes to the members template.

Of course, you can chose how you want to add a delete button, but in this example, we will add a “delete” link for each record in a new table column.

The “delete” link will also contain the ID of each record.


Modify Template

Add a “delete” column in the members template:

members/templates/index.html:

<h1>Members</h1>

<table border="1">
{% for x in mymembers %}
  <tr>
  <td>{{ x.id }}</td>
  <td>{{ x.firstname }}</td>
  <td>{{ x.lastname }}</td>
  <td><a href="delete/{{ x.id }}">delete</a></td>
  </tr>
{% endfor %}
</table>

<p>
<a href="add/">Add member</a>
</p>

The result will look like this:


URLs

The “delete” link in the HTML table points to 127.0.0.1:8000/members/delete/ so we will add a path() function in the members/urls.py file, that points the url to the right location, with the ID as a parameter:

members/urls.py:

from django.urls import path
from . import views

urlpatterns = [
  path('', views.index, name='index'),
  path('add/', views.add, name='add'),
  path('add/addrecord/', views.addrecord, name='addrecord'),
  path('delete/<int:id>', views.delete, name='delete'),
]

Code for Deleting Records

Now we need to add a new view called delete in the members/views.py file:

members/views.py:

from django.http import HttpResponse, HttpResponseRedirect
from django.template import loader
from django.urls import reverse
from .models import Members def index(request): mymembers = Members.objects.all().values() template = loader.get_template('index.html') context = { 'mymembers': mymembers, } return HttpResponse(template.render(context, request)) def add(request): template = loader.get_template('add.html') return HttpResponse(template.render({}, request)) def addrecord(request): x = request.POST['first'] y = request.POST['last'] member = Members(firstname=x, lastname=y) member.save() return HttpResponseRedirect(reverse('index')) def delete(request, id): member = Members.objects.get(id=id) member.delete() return HttpResponseRedirect(reverse('index'))

The delete view does the following:

  • Gets the id as an argument.
  • Uses the id to locate the correct record in the Members table.
  • Deletes that record.
  • Redirects the user back to the index view.

Click on the “delete” link for Jane Doe, and see the result:

Record

Django Update Record

Updating Records

To update a record, we need the ID of the record, and we need a template with an interface that let us change the values.

First we need to make some changes in the index.html template.


Modify Template

Start by adding a link for each member in the table:

members/templates/index.html:

<h1>Members</h1>

<table border="1">
{% for x in mymembers %}
<tr>
<td><a href="update/{{ x.id }}">{{ x.id }}</a></td>
<td>{{ x.firstname }}</td>
<td>{{ x.lastname }}</td>
<td><a href="delete/{{ x.id }}">delete</a>
</tr>
{% endfor %}
</table>

<p>
<a href="add/">Add member</a>
</p>

The link goes to a view called update with the ID of the current member.

The result will look like this:


View

Next, add the update view in the members/views.py file:

members/views.py:

from django.http import HttpResponse, HttpResponseRedirect
from django.template import loader
from django.urls import reverse
from .models import Members

def index(request):
  mymembers = Members.objects.all().values()
  template = loader.get_template('index.html')
  context = {
    'mymembers': mymembers
  }
  return HttpResponse(template.render(context, request))
  
def add(request):
  template = loader.get_template('add.html')
  return HttpResponse(template.render({}, request))
  
 def addrecord(request):
  first = request.POST['first']
  last = request.POST['last']
  member = Members(firstname=first, lastname=last)
  member.save()
  
return HttpResponseRedirect(reverse('index'))

def delete(request, id):
  member = Members.objects.get(id=id)
  member.delete()
  return HttpResponseRedirect(reverse('index'))
  
def update(request, id):
  mymember = Members.objects.get(id=id)
  template = loader.get_template('update.html')
  context = {
    'mymember': mymember,
  }
  return HttpResponse(template.render(context, request))

The update view does the following:

  • Gets the id as an argument.
  • Uses the id to locate the correct record in the Members table.
  • loads a template called update.html.
  • Creates an object containing the member.
  • Sends the object to the template.
  • Outputs the HTML that is rendered by the template.

New Template

Add a new template in the templates folder, named update.html:

members/templates/update.html:

<h1>Update member</h1>

<form action="updaterecord/{{ mymember.id }}" method="post">
{% csrf_token %}
First Name:<br>
<input name="first" value="{{ mymember.firstname }}">
<br><br>
Last Name:<br>
<input name="last" value="{{ mymember.lastname }}">
<br><br>
<input type="submit" value="Submit">
</form>

The template contains an HTML form with the values from the selected member.

Note: Django requires this line in the form:
{% csrf_token %}
to handle Cross Site Request Forgeries in forms where the method is POST.


URLs

Add a path() function in the members/urls.py file, that points the url 127.0.0.1:8000/members/update/ to the right location, with the ID as a parameter:

members/urls.py:

from django.urls import path

from . import views

urlpatterns = [
  path('', views.index, name='index'),
  path('add/', views.add, name='add'),
  path('add/addrecord/', views.addrecord, name='addrecord'),
  path('delete/<int:id>', views.delete, name='delete'),
  path('update/<int:id>', views.update, name='update'),
]

In the browser, click the ID of the member you want to change and the result should look like this:


What Happens on Submit?

Did you notice the action attribute in the HTML form? The action attribute specifies where to send the form data, in this case the form data will be sent to:
updaterecord/{{ mymember.id }}, so we must add a path() function in the members/urls.py file that points to the right view:

members/urls.py:

from django.urls import path

from . import views

urlpatterns = [
  path('', views.index, name='index'),
  path('add/', views.add, name='add'),
  path('add/addrecord/', views.addrecord, name='addrecord'),
  path('delete/<int:id>', views.delete, name='delete'),
  path('update/<int:id>', views.update, name='update'),
  path('update/updaterecord/<int:id>', views.updaterecord, name='updaterecord'),
]

Code for Updating Records

So far we have made the user interface, and we point the URL to the view called updaterecord, but we have not made the view yet.

Make sure you add the updaterecord view in the in the members/views.py file:

members/views.py:

from django.http import HttpResponse, HttpResponseRedirect
from django.template import loader
from django.urls import reverse
from .models import Members

def index(request):
  mymembers = Members.objects.all().values()
  template = loader.get_template('index.html')
  context = {
    'mymembers': mymembers,
  }
  return HttpResponse(template.render(context, request))
  
def add(request):
  template = loader.get_template('add.html')
  return HttpResponse(template.render({}, request))
  
def addrecord(request):
  x = request.POST['first']
  y = request.POST['last']
  member = Members(firstname=x, lastname=y)
  member.save()
  return HttpResponseRedirect(reverse('index'))
  
def delete(request, id):
  member = Members.objects.get(id=id)
  member.delete()
  return HttpResponseRedirect(reverse('index'))
  
def update(request, id):
  mymember = Members.objects.get(id=id)
  template = loader.get_template('update.html')
  context = {
    'mymember': mymember,
  }
  return HttpResponse(template.render(context, request))
  
def updaterecord(request, id):
  first = request.POST['first']
  last = request.POST['last']
  member = Members.objects.get(id=id)
  member.firstname = first
  member.lastname = last
  member.save()
  return HttpResponseRedirect(reverse('index'))

The updaterecord function will update the record in the members table with the selected ID.

Try to update a record and see how it works:

If you press the submit button, the members table should have been updated:

 

Django Templates

Django Template Variables

Template Variables

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

Example

template.html:

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

views.py:

from django.http import HttpResponse
from django.template import loader

def testing(request):
  template = loader.get_template('template.html')
  context = {
    'firstname': 'Linus',
  }
  return HttpResponse(template.render(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 template.render() function.


Create Variables in Template

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

Example

template.html:

{% 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 Members, we will use this model in the next chapters of this tutorial.

To get data from the Memebers model, we will have to import it in the views file, and extract data from it in the view:

views.py:

from django.http import HttpResponse, HttpResponseRedirect
from django.template import loader
from .models import Members

def testing(request):
  mymembers = Members.objects.all().values()
  template = loader.get_template('template.html')
  context = {
    'mymembers': mymembers,
  }
  return HttpResponse(template.render(context, request))

Now we can use the data in the template:

template.html:

<ul>
  {% for x in mymembers %}
    <li>{{ x.firstname }}</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.

Django Template Tags

Template Tags

In Django templates, you can perform programming logic like executing if statements and for loops.

These keywords, if and for, are called “template tags” in Django.

To execute template tags, we surrond them in {% %} brackets.

Example

template.html:

{% if greeting == 1 %}
  <h1>Hello</h1>
{% else %}
  <h1>Bye</h1>
{% endif %}
Run Example »

Django Code

The template tags are a way of telling Django that here comes something else than plain HTML.

The template tags allows us to to do some programming on the server before sending HTML to the client.

template.html:

<ul>
  {% for x in mymembers %}
    <li>{{ x.firstname }}</li>
  {% endfor %}
</ul>
Run Example »

In the next chapters you will learn about the most common template tags.


Tag Reference

A list of all template tags:

TagDescription
autoescapeSpecifies if autoescape mode is on or off
blockSpecifies a block section
commentSpecifies a comment section
csrf_tokenProtects forms from Cross Site Request Forgeries
cycleSpecifies content to use in each cycle of a loop
debugSpecifies debugging information
extendsSpecifies a parent template
filterFilters content before returning it
firstofReturns the first not empty variable
forSpecifies a for loop
ifSpecifies a if statement
ifchangedUsed in for loops. Outputs a block only if a value has changed since the last iteration
includeSpecifies included content/template
loadLoads template tags from another library
loremOutputs random text
nowOutputs the current date/time
regroupSorts an object by a group
resetcycleUsed in cycles. Resets the cycle
spacelessRemoves whitespace between HTML tags
templatetagOutputs a specified template tag
urlReturns the absolute URL part of a URL
verbatimSpecifies contents that should not be rendered by the template engine
widthratioCalculates a width value based on the ration between a given value and a max value
withSpecifies a variable to use in the block

Django if Tag

If Statement

An if statement evaluates a variable and executes a block of code if the value is true.

Example

{% if greeting == 1 %}
  <h1>Hello</h1>
{% endif %} 
Run Example »

Elif

The elif keyword says “if the previous conditions were not true, then try this condition”.

Example

{% if greeting == 1 %}
  <h1>Hello</h1>
{% elif greeting == 2 %}
  <h1>Welcome</h1>
{% endif %} 
Run Example »

Else

The else keyword catches anything which isn’t caught by the preceding conditions.

Example

{% if greeting == 1 %}
  <h1>Hello</h1>
{% elif greeting == 2 %}
  <h1>Welcome</h1>
{% else %}
  <h1>Goodbye</h1>
{% endif %} 
Run Example »

Operators

The above examples uses the == operator, which is used to check if a variable is equal to a value, but there are many other operators you can use, or you can even drop the operator if you just want to check if a variable is not empty:

Example

{% if greeting %}
  <h1>Hello</h1>
{% endif %} 
Run Example »

==

Is equal to.

Example

{% if greeting == 2 %}
  <h1>Hello</h1>
{% endif %} 
Run Example »

!=

Is not equal to.

Example

{% if greeting != 1 %}
  <h1>Hello</h1>
{% endif %} 
Run Example »

<

Is less than.

Example

{% if greeting < 3 %}
  <h1>Hello</h1>
{% endif %} 
Run Example »

<=

Is less than, or equal to.

Example

{% if greeting <= 3 %}
  <h1>Hello</h1>
{% endif %} 
Run Example »

>

Is greater than.

Example

{% if greeting > 1 %}
  <h1>Hello</h1>
{% endif %} 
Run Example »

>=

Is greater than, or equal to.

Example

{% if greeting >= 1 %}
  <h1>Hello</h1>
{% endif %} 
Run Example »

and

To check if more than one condition is true.

Example

{% if greeting == 1 and day == "Friday" %}
  <h1>Hello Weekend!</h1>
{% endif %} 
Run Example »

or

To check if one of the conditions is true.

Example

{% if greeting == 1 or greeting == 5 %}
  <h1>Hello</h1>
{% endif %} 
Run Example »

and/or

Combine and and or.

Example

{% if greeting == 1 and day == "Friday" or greeting == 5 %}
Run Example »

Parentheses are not allowed in if statements in Django, so when you combine and and or operators, it is important to know that parentheses are added for and but not for or.

Meaning that the above example is read by the interpreter like this:

{% if (greeting == 1 and day == "Friday") or greeting == 5 %}

in

To check if a certain item is present in an object.

Example

{% if 'Banana' in fruits %}
  <h1>Hello</h1>
{% else %}
  <h1>Goodbye</h1>
{% endif %} 
Run Example »

not in

To check if a certain item is not present in an object.

Example

{% if 'Banana' not in fruits %}
  <h1>Hello</h1>
{% else %}
  <h1>Goodbye</h1>
{% endif %} 
Run Example »

is

Check if two objects are the same.

This operator is different from the == operator, because the == operator checks the values of two objects, but the is operator checks the identity of two objects.

In the view we have two objects, x and y, with the same values:

Example

views.py:

from django.http import HttpResponse
from django.template import loader

def testing(request):
  template = loader.get_template('template.html')
  context = {
    'x': ['Apple', 'Banana', 'Cherry'], 
    'y': ['Apple', 'Banana', 'Cherry'], 
  }
  return HttpResponse(template.render(context, request))  

The two objects have the same value, but is it the same object?

Example

{% if x is y %}
  <h1>YES</h1>
{% else %}
  <h1>NO</h1>
{% endif %}
Run Example »

Let us try the same example with the == operator instead:

Example

{% if x == y %}
  <h1>YES</h1>
{% else %}
  <h1>NO</h1>
{% endif %}
Run Example »

How can two objects be the same? Well, if you have two objects that points to the same object, then the is operator evaluates to true:

We will demonstrate this by using the {% with %} tag, which allows us to create variables in the template:

Example

{% with var1=x var2=x %}
  {% if var1 == var2 %}
    <h1>YES</h1>
  {% else %}
    <h1>NO</h1>
  {% endif %}
{% endwith %}
Run Example »

is not

To check if two objects are not the same.

Example

{% if x is not y %}
  <h1>YES</h1>
{% else %}
  <h1>NO</h1>
{% endif %} 

Django for Tag

For Loops

for loop is used for iterating over a sequence, like looping over items in an array, a list, or a dictionary.

Example

Loop through the items of a list:

{% for x in fruits %}
  <h1>{{ x }}</h1>
{% endfor %}
Run Example »

Example

Loop through a list of dictionaries:

{% for x in cars %}
  <h1>{{ x.brand }}</h1>
  <p>{{ x.model }}</p>
  <p>{{ x.year }}</p>
{% endfor %} 
Run Example »

Data From a Model

Data in a model is like a table with rows and columns.

The Members model we created earlier has five rows, and each row has three columns:

 id  firstname  lastname 
 1  Emil  Refsnes 
 2  Tobias  Refsnes 
 3  Linus  Refsnes 
 4  Lene  Refsnes 
 5  Stalikken  Refsnes 

When we fetch data from the model, it comes as a QuerySet object, with a similar format as the cars example above: a list with dictionaries:

<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'
  }
]> 

Example

Loop through items fetched from a database:

{% for x in members %}
  <h1>{{ x.id }}</h1>
  <p>
    {{ x.firstname }}
    {{ x.lastname }}
  </p>
{% endfor %} 
Run Example »

Reversed

The reversed keyword is used when you want to do the loop in reversed order.

Example

{% for x in members reversed %}
  <h1>{{ x.id }}</h1>
  <p>
    {{ x.firstname }}
    {{ x.lastname }}
  </p>
{% endfor %}  
Run Example »

Empty

The empty keyword can be used if you want to do something special if the object is empty.

Example

<ul>
  {% for x in emptytestobject %}
    <li>{{ x.firstname }}</li>
  {% empty %}
    <li>No members</li>
  {% endfor %}
</ul> 
Run Example »

The empty keyword can also be used if the object does not exist:

Example

<ul>
  {% for x in myobject %}
    <li>{{ x.firstname }}</li>
  {% empty %}
    <li>No members</li>
  {% endfor %}
</ul> 
Run Example »

Loop Variables

Django has some variables that are available for you inside a loop:

  • forloop.counter
  • forloop.counter0
  • forloop.first
  • forloop.last
  • forloop.parentloop
  • forloop.revcounter
  • forloop.revcounter0

forloop.counter

The current iteration, starting at 1.

Example

<ul>
  {% for x in fruits %}
    <li>{{ forloop.counter }}</li>
  {% endfor %}
</ul> 
Run Example »

forloop.counter0

The current iteration, starting at 0.

Example

<ul>
  {% for x in fruits %}
    <li>{{ forloop.counter0 }}</li>
  {% endfor %}
</ul> 
Run Example »

forloop.first

Allows you to test if the loop is on its first iteration.

Example

Draw a blue background for the first iteration of the loop:

<ul>
  {% for x in fruits %}
    <li
      {% if forloop.first %}
        style='background-color:lightblue;'
      {% endif %}
    >{{ x }}</li>
  {% endfor %}
</ul> 
Run Example »

forloop.last

Allows you to test if the loop is on its last iteration.

Example

Draw a blue background for the last iteration of the loop:

<ul>
  {% for x in fruits %}
    <li
      {% if forloop.last %}
        style='background-color:lightblue;'
      {% endif %}
    >{{ x }}</li>
  {% endfor %}
</ul> 
Run Example »

forloop.revcounter

The current iteration if you start at the end and count backwards, ending up at 1.

Example

<ul>
  {% for x in fruits %}
    <li>{{ forloop.revcounter }}</li>
  {% endfor %}
</ul> 
Run Example »

forloop.revcounter0

The current iteration if you start at the end and count backwards, ending up at 0.

Example

<ul>
  {% for x in fruits %}
    <li>{{ forloop.revcounter0 }}</li>
  {% endfor %}
</ul> 
Run Example »

Django comment Tag

Comments

Comments allows you to have sections of code that should be ignored.

Example

<h1>Welcome Everyone</h1>
{% comment %}
  <h1>Welcome ladies and gentlemen</h1>
{% endcomment %}
Run Example »

Comment Description

You can add a message to your comment, to help you remember why you wrote the comment, or as message to other people reading the code.

Example

Add a description to you comment:

<h1>Welcome Everyone</h1>
{% comment "this was the original welcome message" %}
    <h1>Welcome ladies and gentlemen</h1>
{% endcomment %}
Run Example »

Smaller Comments

You can also use the {# ... #} tags when commenting out code, which can be easier when for smaller comments:

Example

Comment out the word Everyone:

<h1>Welcome{# Everyone#}</h1>
Run Example »

Comment in Views

Views are written in Python, and Python comments are written with the # character:

Example

Comment out a section in the view:

from django.http import HttpResponse
from django.template import loader

def testing(request):
  template = loader.get_template('template.html')
  #context = {
  # 'var1': 'John',
  #}
  return HttpResponse(template.render())
Run Example »

Read more about Python Comments in out Python Comment Tutorial.

Django cycle Tag

Cycles

The cycle tag allows you to do different tasks for different iterations.

The cycle tag takes arguments, the first iteration uses the first argument, the second iteration uses the second argument etc.

{% cycle 'lightblue' 'pink' 'yellow' 'coral' 'grey' %}

If you want to have a new background color for each iteration, you can do that with the cycle tag:

Example

<ul>
  {% for x in members %}
    <li style='background-color:{% cycle 'lightblue' 'pink' 'yellow' 'coral' 'grey' %}'>
      {{ x.firstname }}
    </li>
  {% endfor %}
</ul> 
Run Example »

If the cycle reaches the end of the arguments, it starts over:

Example

<ul>
  {% for x in members %}
    <li style='background-color:{% cycle 'lightblue' 'pink' %}'>
      {{ x.firstname }}
    </li>
  {% endfor %}
</ul> 
Run Example »

Cycle Arguments as Variable

In the first example the argument values was displayed directly in the cycle, but you can also keep the argument values in a variable, and use it later:

Example

Store the color values in a variable named bgcolor, and use it as a background color later in the loop:

<ul>
  {% for x in members %}
    {% cycle 'lightblue' 'pink' 'yellow' 'coral' 'grey' as bgcolor silent %}
    <li style='background-color:{{ bgcolor }}'>
      {{ x.firstname }}
    </li>
  {% endfor %}
</ul> 
Run Example »

Did you notice the silent keyword? Make sure you add this, or else the argument values will be displayed twice in the output:

Example

Same example as above, but without the silent keyword:

<ul>
  {% for x in members %}
    {% cycle 'lightblue' 'pink' 'yellow' 'coral' 'grey' as bgcolor %}
    <li style='background-color:{{ bgcolor }}'>
      {{ x.firstname }}
    </li>
  {% endfor %}
</ul> 
Run Example »

Reset Cycle

You can force the cycle to restart by using the {% resetcycle %} tag:

Example

Restart the cycle after 3 cycles:

<ul>
  {% for x in members %}
    {% cycle 'lightblue' 'pink' 'yellow' 'coral' 'grey' as bgcolor silent %}
    {% if forloop.counter == 3 %}
      {% resetcycle %}
    {% endif %}
    <li style='background-color:{{ bgcolor }}'>
      {{ x.firstname }}
    </li>
  {% endfor %}
</ul> 
Run Example »

Django extends Tag

Extends

The extends tag allows you to add a parent template for the current template.

This means that you can have one master page that acts like a parent for all other pages:

Example

mymaster.html:

<html>
<body>

<h1>Welcome</h1>

{% block mymessage %}
{% endblock %}

</body>
</html> 

template.html:

{% extends 'mymaster.html' %}

{% block mymessage %}
  <p>This page has a master page</p>
{% endblock %} 
Run Example »

You put placeholders in the master template, telling Django where to put which content.

Django uses the {% block %} tag, to create placeholders:

master.html:

<html>
<body>

{% block myheading %}
{% endblock %}

{% block mymessage %}
{% endblock %}

</body>
</html> 

Templates that uses the master template, uses the {% block %} tag to create content that will be displayed in the placeholder with the same name:

template.html:

{% extends 'mymaster.html' %}

{% block myheading %}
  <h1>Members</h1>
{% endblock %}

{% block mymessage %}
  <ul>
    {% for x in members %}
      <li>{{ x.firstname }}</li>
    {% endfor %}
  </ul>
{% endblock %} 
Run Example »

Django include Tag

Include

The include tag allows you include a template inside the current template.

This is useful when you have a block of content that are the same for many pages.

Example

footer.html:

<p>You have reach the bottom of this page, thank you for your time.</p>

template.html:

<h1>Hello</h1>

<p>This page contains a footer in a template.</p>

{% include 'footer.html' %} 
Run Example »

Variables in Include

You can send variables into the template by using the with keyword.

In the include file, you refer to the variables by using the {{ variablename }} syntax:

Example

mymenu.html:

<div>HOME | {{ me }} | ABOUT | FORUM | {{ sponsor }}</div>

template.html:

<!DOCTYPE html>
<html>
<body>

{% include mymenu.html with me="TOBIAS" sponsor="W3SCHOOLS" %}

<h1>Welcome</h1>

<p>This is my webpage</p>

</body>
</html> 
Run Example »

Django filter Tag

Filter a Value

With the pipe | character followed by a filter name, you can run a value through a filter before returning it.

The name of the filter defines what the filter will do with the value.

Example

Return the variable firstname with upper case letters:

<h1>Hello {{ firstname|upper }}, how are you?</h1>
Run Example »

The filter Tag

The filter tag allows you to run a whole section of code through a filter, and return it according to the filter keyword(s).

Example

Return the variable firstname with upper case letters:

{% filter upper %}
  <h1>Hello everyone, how are you?</h1>
{% endfilter %}
Run Example »

To add multiple filters, separate the keywords with the pipe | character:

Example

Separate filters with the pipe character:

{% filter upper|linenumbers %}Hello!
my name is
Emil.
What is your name?{% endfilter %}
Run Example »

Filter Reference

A list of all filter keywords:

KeywordDescription
addAdds a specified value.
addslashesAdds a slash before any quote characters, to escape strings.
capfirstReturns the first letter in uppercase.
centerCenters the value in the middle of a specified width.
cutRemoves any specified character or phrases.
dateReturns dates in the specified format.
defaultReturns a specified value if the value is False.
default_if_noneReturns a specified value if the value is None.
dictsortSorts a dictionary by the given value.
dictsortreversedSorts a dictionary reversed, by the given value.
divisiblebyReturns True if the value can be divided by the specified number, otherwise it returns False.
escapeEscapes HTML code from a string.
escapejsEscapes JavaScript code from a string.
filesizeformatReturns a number into a file size format.
firstReturns the first item of an object (for Strings, the first character is returned).
floatformatRounds floating numbers to a specified number of decimals, default one decimal.
force_escapeEscapes HTML code from a string.
get_digitReturns a specific digit of a number.
iriencodeConvert an IRI into a URL friendly string.
joinReturns the items of a list into a string.
json_scriptReturns an object into a JSON object surrounded by <script></script> tags.
lastReturns the last item of an object (for Strings, the last character is returned).
lengthReturns the number of items in an object, or the number of characters in a string.
length_isReturns True if the length is the same as the specified nuymber
linebreaksReturns the text with <br> instead of line breaks, and <p> instead of more than one linebreak.
linebreaksbrReturns the text with <br> instead of line breaks.
linenumbersReturns the text with line numbers for each line.
ljustLeft aligns the value according to a specified width
lowerReturns the text in lower case letters.
make_listConverts a value into a list object.
phone2numericConverts phone numbers with letters into numeric phone numbers.
pluralizeAdds a ‘s’ at the end of  of a value if the specified numeric value is not 1.
pprint 
randomReturns a random item of an object
rjustRight aligns the value according to a specified width
safeMarks that this text is safe and should not be HTML escaped.
safeseqMarks each item of an object as safe and the item should not be HTML escaped.
sliceReturns a specified slice of a text or object.
slugifyConverts text into one long alphanumeric-lower-case word.
stringformatConverts the value into a specified format.
striptagsRemoves HTML tags from a text.
timeReturns a time in the specified format.
timesinceReturns the difference between two datetimes.
timeuntilReturns the difference between two datetimes.
titleUpper cases the first character of each word in a text, all other characters are converted to lower case.
truncatecharsShortens a string into the specified number of characters.
truncatechars_htmlShortens a string into the specified number of characters, not considering the length of any HTML tags.
truncatewordsShortens a string into the specified number of words.
truncatewords_htmlShortens a string into the specified number of words, not considering any HTML tags.
unordered_listReturns the items of an object as an unordered HTML list.
upperReturns the text in upper case letters.
urlencodeURL encodes a string.
urlizeReturns any URLs in a string as HTML links.
urlizetruncReturns any URLs in a string as HTML links, but shortens the links into the specified number of characters.
wordcountReturns the number of words in a text.
wordwrapWrap words at a specified number of characters.
yesnoConverts Booleans values into specified values.
i18n 
l10n 
tz 

Django QuerySets

Django QuerySet

Django QuerySet

A QuerySet is a collection of data from a database.

A QuerySet is built up as a list of objects.

QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.

In this tutorial we will be querying data from the Members table.

Members:

idfirstnamelastname
1EmilRefsnes
2TobiasRefsnes
3LinusRefsnes
4LeneRefsnes
5StalikkenRefsnes

Querying Data

In views.py, we have a view for testing called testing where we will test different queries.

In the example below we use the .all() method to get all the records and fields of the Members model:

View

members/views.py:

from django.http import HttpResponse
from django.template import loader
from .models import Members

def testing(request):
  mydata = Members.objects.all()
  template = loader.get_template('template.html')
  context = {
    'mymembers': mydata,
  }
  return HttpResponse(template.render(context, request))

The object is placed in a variable called mydata, and is sent to the template via the context object as mymembers, and looks like this:

<QuerySet [
  <Members: Members object (1)>,
  <Members: Members object (2)>,
  <Members: Members object (3)>,
  <Members: Members object (4)>,
  <Members: Members object (5)>
]>

As you can see, our Members model contains 5 records, and are listed inside the QuerySet as 5 objects.

In the template you can use the mymembers object to generate content:

Template

template.html:

<table border='1'>
  <tr>
    <th>ID</th>
    <th>Firstname</th>
    <th>Lastname</th>
  </tr>
  {% for x in mymembers %}
    <tr>
      <td>{{ x.id }}</td>
        <td>{{ x.firstname }}</td>
      <td>{{ x.lastname }}</td>
    </tr>
  {% endfor %}
</table>
Run Example »

Django QuerySet Get Data

Get Data

There are different methods to get data from a model into a QuerySet.


The values() Method

The values() method allows you to return each object as a Python dictionary, with the names and values as key/value pairs:

View

members/views.py:

from django.http import HttpResponse
from django.template import loader
from .models import Members

def testing(request):
  mydata = Members.objects.all().values()
  template = loader.get_template('template.html')
  context = {
    'mymembers': mydata,
  }
  return HttpResponse(template.render(context, request))
Run Example »

Return Specific Columns

The values_list() method allows you to return only the columns that you specify.

View

members/views.py:

from django.http import HttpResponse
from django.template import loader
from .models import Members

def testing(request):
  mydata = Members.objects.values_list('firstname')
  template = loader.get_template('template.html')
  context = {
    'mymembers': mydata,
  }
  return HttpResponse(template.render(context, request))
Run Example »

Return Specific Rows

You can filter the search to only return specific rows/records, by using the filter() method.

View

members/views.py:

from django.http import HttpResponse
from django.template import loader
from .models import Members

def testing(request):
  mydata = Members.objects.filter(firstname='Emil').values()
  template = loader.get_template('template.html')
  context = {
    'mymembers': mydata,
  }
  return HttpResponse(template.render(context, request))
Run Example »

You will learn more about the filter() method in the next chapter.

Django QuerySet Filter

Django QuerySet Filter

The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.

As we learned in the previous chapter, we can filter on field names like this:

Example

Return only the records where the firstname is ‘Emil’:

mydata = Members.objects.filter(firstname='Emil').values()
Run Example »

In SQL, the above statement would be written like this:

SELECT * FROM members WHERE firstname = 'Emil';

AND

The filter() method takes the arguments as **kwargs (keyword arguments), so you can filter on more than one field by sepearting them by a comma.

Example

Return records where lastname is “Refsnes” and id is 2:

mydata = Members.objects.filter(lastname='Refsnes', id=2).values()
Run Example »

In SQL, the above statement would be written like this:

SELECT * FROM members WHERE   lastname = 'Refsnes' AND id = 2;

OR

To return records where firstname is Emil or firstname is Tobias (meaning: returning records that matches either query, not necessarily both) is not as easy as the AND example above.

We can use multiple filter() methods, separated by a pipe | character. The results will merge into one model.

Example

Return records where firstname is either “Emil” or Tobias”:

mydata = Members.objects.filter(firstname='Emil').values() | Members.objects.filter(firstname='Tobias').values()
Run Example »

Another common method is to import and use Q expressions:

Example

Return records where firstname is either “Emil” or Tobias”:

from django.http import HttpResponse
from django.template import loader
from .models import Members
from django.db.models import Q

def testing(request):
  mydata = Members.objects.filter(Q(firstname='Emil') | Q(firstname='Tobias')).values()
  template = loader.get_template('template.html')
  context = {
    'mymembers': mydata,
  }
  return HttpResponse(template.render(context, request))
Run Example »

In SQL, the above statement would be written like this:

SELECT * FROM members WHERE   firstname = 'Emil' OR firstname = 'Tobias';

Field Lookups

Django has its own way of specifying SQL statements and WHERE clauses.

To make specific where clasuses in Django, use “Field lookups”.

Field lookups are keywords that represents specific SQL keywords.

Example:

.filter(firstname__startswith='L');

Is the same as the SQL statment:

WHERE firstname LIKE '%L'

The above statement will return records where firstname starts with ‘L’.

Field Lookups Syntax

All Field lookup keywords must be specified with the fieldname, followed by two(!) underscore characters, and the keyword.

In our Members model, the statement would be written like this:

Example

Return the records where firstname starts with the letter ‘L’:

mydata = Members.objects.filter(firstname__startswith='L').values()
Run Example »

Field Lookups Reference

A list of all field look up keywords:

KeywordDescription
containsContains the phrase
icontainsSame as contains, but case-insensitive
dateMatches a date
dayMatches a date (day of month, 1-31) (for dates)
endswidthEnds with
iendswidthSame as endswidth, but case-insensitive
exactAn exact match
iexactSame as exact, but case-insensitive
inMatches one of the values
isnullMatches NULL values
gtGreater than
gteGreater than, or equal to
hourMatches an hour (for datetimes)
ltLess than
lteLess than, or equal to
minuteMatches a minute (for datetimes)
monthMatches a month (for dates)
quarterMatches a quarter of the year (1-4) (for dates)
rangeMatch between
regexMatches a regular expression
iregexSame as regex, but case-insensitive
secondMatches a second (for datetimes)
startswidthStarts width
istartswidthSame as startswidth, but case-insensitive
timeMatches a time (for datetimes)
weekMatches a week number (1-53) (for dates)
week_dayMatches a day of week (1-7) 1 is sunday
iso_week_dayMatches a ISO 8601 day of week (1-7) 1 is monday
yearMatches a year (for dates)
iso_yearMatches an ISO 8601 year (for dates)
 

Django QuerySet Order By

Order By

To sort QuerySets, Django uses the order_by() method:

Example

Order the the result alphabetically by firstname:

mydata = Members.objects.all().order_by('firstname').values()

Result

<QuerySet [
  {‘id’: 1, ‘firstname’: ‘Emil’, ‘lastname’: ‘Refsnes’},
  {‘id’: 4, ‘firstname’: ‘Lene’, ‘lastname’: ‘Refsnes’},
  {‘id’: 3, ‘firstname’: ‘Linus’, ‘lastname’: ‘Refsnes’},
  {‘id’: 5, ‘firstname’: ‘Stalikken’, ‘lastname’: ‘Refsnes’},
  {‘id’: 2, ‘firstname’: ‘Tobias’, ‘lastname’: ‘Refsnes’}
]>

In SQL, the above statement would be written like this:

SELECT * FROM members ORDER BY firstname;
>

Descending Order

By default, the result is sorted ascending (the lowest value first), to change the direction to descending (the highest value first), use the minus sign (NOT), - in front of the field name:

Example

Order the the result firstname descending:

mydata = Members.objects.all().order_by('-firstname').values()

Result

<QuerySet [
  {‘id’: 2, ‘firstname’: ‘Tobias’, ‘lastname’: ‘Refsnes’},
  {‘id’: 5, ‘firstname’: ‘Stalikken’, ‘lastname’: ‘Refsnes’},
  {‘id’: 3, ‘firstname’: ‘Linus’, ‘lastname’: ‘Refsnes’},
  {‘id’: 4, ‘firstname’: ‘Lene’, ‘lastname’: ‘Refsnes’},
  ‘id’: 1, ‘firstname’: ‘Emil’, ‘lastname’: ‘Refsnes’}
]>

In SQL, the above statement would be written like this:

SELECT * FROM members ORDER BY firstname DESC;

Multiple Order Bys

To order by more than one field, separate the fieldnames with a comma in the order_by() method:

Example

Order the the result first by lastname ascending, then descending on id:

mydata = Members.objects.all().order_by('lastname', '-id').values()

Result

<QuerySet [
  {‘id’: 5, ‘firstname’: ‘Stalikken’, ‘lastname’: ‘Refsnes’},
  {‘id’: 4, ‘firstname’: ‘Lene’, ‘lastname’: ‘Refsnes’},
  {‘id’: 3, ‘firstname’: ‘Linus’, ‘lastname’: ‘Refsnes’},
  {‘id’: 2, ‘firstname’: ‘Tobias’, ‘lastname’: ‘Refsnes’},
  {‘id’: 1, ‘firstname’: ‘Emil’, ‘lastname’: ‘Refsnes’}
]>

In SQL, the above statement would be written like this:

SELECT * FROM members ORDER BY lastname ASC, id DESC;

Django References

Django Template Tags Reference

Template Tags Reference

A list of all template tags:

TagDescription
autoescapeSpecifies if autoescape mode is on or off
blockSpecifies a block section
commentSpecifies a comment section
csrf_tokenProtects forms from Cross Site Request Forgeries
cycleSpecifies content to use in each cycle of a loop
debugSpecifies debugging information
extendsSpecifies a parent template
filterFilters content before returning it
firstofReturns the first not empty variable
forSpecifies a for loop
ifSpecifies a if statement
ifchangedUsed in for loops. Outputs a block only if a value has changed since the last iteration
includeSpecifies included content/template
loadLoads template tags from another library
loremOutputs random text
nowOutputs the current date/time
regroupSorts an object by a group
resetcycleUsed in cycles. Resets the cycle
spacelessRemoves whitespace between HTML tags
templatetagOutputs a specified template tag
urlReturns the absolute URL part of a URL
verbatimSpecifies contents that should not be rendered by the template engine
widthratioCalculates a width value based on the ration between a given value and a max value
withSpecifies a variable to use in the block

Filter Reference

Filter Reference

A list of all filter keywords:

KeywordDescription
addAdds a specified value.
addslashesAdds a slash before any quote characters, to escape strings.
capfirstReturns the first letter in uppercase.
centerCenters the value in the middle of a specified width.
cutRemoves any specified character or phrases.
dateReturns dates in the specified format.
defaultReturns a specified value if the value is False.
default_if_noneReturns a specified value if the value is None.
dictsortSorts a dictionary by the given value.
dictsortreversedSorts a dictionary reversed, by the given value.
divisiblebyReturns True if the value can be divided by the specified number, otherwise it returns False.
escapeEscapes HTML code from a string.
escapejsEscapes JavaScript code from a string.
filesizeformatReturns a number into a file size format.
firstReturns the first item of an object (for Strings, the first character is returned).
floatformatRounds floating numbers to a specified number of decimals, default one decimal.
force_escapeEscapes HTML code from a string.
get_digitReturns a specific digit of a number.
iriencodeConvert an IRI into a URL friendly string.
joinReturns the items of a list into a string.
json_scriptReturns an object into a JSON object surrounded by <script></script> tags.
lastReturns the last item of an object (for Strings, the last character is returned).
lengthReturns the number of items in an object, or the number of characters in a string.
length_isReturns True if the length is the same as the specified nuymber
linebreaksReturns the text with <br> instead of line breaks, and <p> instead of more than one linebreak.
linebreaksbrReturns the text with <br> instead of line breaks.
linenumbersReturns the text with line numbers for each line.
ljustLeft aligns the value according to a specified width
lowerReturns the text in lower case letters.
make_listConverts a value into a list object.
phone2numericConverts phone numbers with letters into numeric phone numbers.
pluralizeAdds a ‘s’ at the end of  of a value if the specified numeric value is not 1.
pprint 
randomReturns a random item of an object
rjustRight aligns the value according to a specified width
safeMarks that this text is safe and should not be HTML escaped.
safeseqMarks each item of an object as safe and the item should not be HTML escaped.
sliceReturns a specified slice of a text or object.
slugifyConverts text into one long alphanumeric-lower-case word.
stringformatConverts the value into a specified format.
striptagsRemoves HTML tags from a text.
timeReturns a time in the specified format.
timesinceReturns the difference between two datetimes.
timeuntilReturns the difference between two datetimes.
titleUpper cases the first character of each word in a text, all other characters are converted to lower case.
truncatecharsShortens a string into the specified number of characters.
truncatechars_htmlShortens a string into the specified number of characters, not considering the length of any HTML tags.
truncatewordsShortens a string into the specified number of words.
truncatewords_htmlShortens a string into the specified number of words, not considering any HTML tags.
unordered_listReturns the items of an object as an unordered HTML list.
upperReturns the text in upper case letters.
urlencodeURL encodes a string.
urlizeReturns any URLs in a string as HTML links.
urlizetruncReturns any URLs in a string as HTML links, but shortens the links into the specified number of characters.
wordcountReturns the number of words in a text.
wordwrapWrap words at a specified number of characters.
yesnoConverts Booleans values into specified values.
i18n 
l10n 
tz 

QuerySet Field Lookups Reference

Field Lookups Reference

A list of all field look up keywords:

KeywordDescription
containsContains the phrase
icontainsSame as contains, but case-insensitive
dateMatches a date
dayMatches a date (day of month, 1-31) (for dates)
endswidthEnds with
iendswidthSame as endswidth, but case-insensitive
exactAn exact match
iexactSame as exact, but case-insensitive
inMatches one of the values
isnullMatches NULL values
gtGreater than
gteGreater than, or equal to
hourMatches an hour (for datetimes)
ltLess than
lteLess than, or equal to
minuteMatches a minute (for datetimes)
monthMatches a month (for dates)
quarterMatches a quarter of the year (1-4) (for dates)
rangeMatch between
regexMatches a regular expression
iregexSame as regex, but case-insensitive
secondMatches a second (for datetimes)
startswidthStarts width
istartswidthSame as startswidth, but case-insensitive
timeMatches a time (for datetimes)
weekMatches a week number (1-53) (for dates)
week_dayMatches a day of week (1-7) 1 is sunday
iso_week_dayMatches a ISO 8601 day of week (1-7) 1 is monday
yearMatches a year (for dates)
iso_yearMatches an ISO 8601 year (for dates)
 

Python 3.10.4

Python Modules

ArmenianChinese (Traditional)EnglishGermanRussian