Django at a glance

    The goal of this document is to give you enough technical specifics to understand how Django works, but this isn’t intended to be a tutorial or reference – but we’ve got both! When you’re ready to start a project, you can start with the tutorial or .

    Although you can use Django without a database, it comes with an object-relational mapper in which you describe your database layout in Python code.

    The offers many rich ways of representing your models – so far, it’s been solving many years’ worth of database-schema problems. Here’s a quick example:

    mysite/news/models.py

    Install it

    Next, run the Django command-line utilities to create the database tables automatically:

    Linux/macOS   Windows

    1. $ python manage.py migrate
    1. ...\> py manage.py makemigrations
    2. ...\> py manage.py migrate

    The command looks at all your available models and creates migrations for whichever tables don’t already exist. migrate runs the migrations and creates tables in your database, as well as optionally providing .

    With that, you’ve got a free, and rich, Python API to access your data. The API is created on the fly, no code generation necessary:

    A dynamic admin interface: it’s not just scaffolding – it’s the whole house

    Once your models are defined, Django can automatically create a professional, production ready administrative interface – a website that lets authenticated users add, change and delete objects. The only step required is to register your model in the admin site:

    mysite/news/models.py

    1. from django.db import models
    2. class Article(models.Model):
    3. headline = models.CharField(max_length=200)
    4. content = models.TextField()
    5. reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)

    mysite/news/admin.py

    1. from django.contrib import admin
    2. from . import models
    3. admin.site.register(models.Article)

    The philosophy here is that your site is edited by a staff, or a client, or maybe just you – and you don’t want to have to deal with creating backend interfaces only to manage content.

    A clean, elegant URL scheme is an important detail in a high-quality web application. Django encourages beautiful URL design and doesn’t put any cruft in URLs, like or .asp.

    To design URLs for an app, you create a Python module called a . A table of contents for your app, it contains a mapping between URL patterns and Python callback functions. URLconfs also serve to decouple URLs from Python code.

    Here’s what a URLconf might look like for the Reporter/Article example above:

    mysite/news/urls.py

    The code above maps URL paths to Python callback functions (“views”). The path strings use parameter tags to “capture” values from the URLs. When a user requests a page, Django runs through each path, in order, and stops at the first one that matches the requested URL. (If none of them matches, Django calls a special-case 404 view.) This is blazingly fast, because the paths are compiled into regular expressions at load time.

    Once one of the URL patterns matches, Django calls the given view, which is a Python function. Each view gets passed a request object – which contains request metadata – and the values captured in the pattern.

    For example, if a user requested the URL “/articles/2005/05/39323/”, Django would call the function news.views.article_detail(request, year=2005, month=5, pk=39323).

    Write your views

    Each view is responsible for doing one of two things: Returning an object containing the content for the requested page, or raising an exception such as Http404. The rest is up to you.

    Generally, a view retrieves data according to the parameters, loads a template and renders the template with the retrieved data. Here’s an example view for year_archive from above:

    mysite/news/views.py

    1. from django.shortcuts import render
    2. from .models import Article
    3. def year_archive(request, year):
    4. a_list = Article.objects.filter(pub_date__year=year)
    5. context = {'year': year, 'article_list': a_list}

    This example uses Django’s , which has several powerful features but strives to stay simple enough for non-programmers to use.

    The code above loads the news/year_archive.html template.

    Let’s say the news/year_archive.html template was found. Here’s what that might look like:

    mysite/news/templates/news/year_archive.html

    1. {% block title %}Articles for {{ year }}{% endblock %}
    2. {% block content %}
    3. <h1>Articles for {{ year }}</h1>
    4. {% for article in article_list %}
    5. <p>{{ article.headline }}</p>
    6. <p>By {{ article.reporter.full_name }}</p>
    7. <p>Published {{ article.pub_date|date:"F j, Y" }}</p>
    8. {% endfor %}
    9. {% endblock %}

    Variables are surrounded by double-curly braces. {{ article.headline }} means “Output the value of the article’s headline attribute.” But dots aren’t used only for attribute lookup. They also can do dictionary-key lookup, index lookup and function calls.

    Note {{ article.pub_date|date:"F j, Y" }} uses a Unix-style “pipe” (the “|” character). This is called a template filter, and it’s a way to filter the value of a variable. In this case, the date filter formats a Python datetime object in the given format (as found in PHP’s date function).

    You can chain together as many filters as you’d like. You can write custom template filters. You can write , which run custom Python code behind the scenes.

    Finally, Django uses the concept of “template inheritance”. That’s what the {% extends "base.html" %} does. It means “First load the template called ‘base’, which has defined a bunch of blocks, and fill the blocks with the following blocks.” In short, that lets you dramatically cut down on redundancy in templates: each template has to define only what’s unique to that template.

    Here’s what the “base.html” template, including the use of static files, might look like:

    mysite/templates/base.html

    Simplistically, it defines the look-and-feel of the site (with the site’s logo), and provides “holes” for child templates to fill. This means that a site redesign can be done by changing a single file – the base template.

    It also lets you create multiple versions of a site, with different base templates, while reusing child templates. Django’s creators have used this technique to create strikingly different mobile versions of sites by only creating a new base template.

    Note that you don’t have to use Django’s template system if you prefer another system. While Django’s template system is particularly well-integrated with Django’s model layer, nothing forces you to use it. For that matter, you don’t have to use Django’s database API, either. You can use another database abstraction layer, you can read XML files, you can read files off disk, or anything you want. Each piece of Django – models, views, templates – is decoupled from the next.

    This is just the surface

    This has been only a quick overview of Django’s functionality. Some more useful features:

    • A caching framework that integrates with memcached or other backends.
    • A that lets you create RSS and Atom feeds by writing a small Python class.