Intermediate   Chapter 178 · 40 min read · Module 14: Advanced Application Development

Django Fundamentals

Learning objectives
  • After this chapter you can describe what Django is and how it differs from a micro framework like Flask.
  • You can explain the Model Template View pattern and the role of each part.
  • You can name the files of a Django project and say what manage.py, settings.py and urls.py do.
  • You can write a simple model, view and URL pattern.
  • You can list the common manage.py commands used to start, migrate and run a project.

Django is a high level web framework for Python. Its slogan promises everything you need to build a serious website, and it keeps that promise: it comes with an object relational mapper for databases, a login system, forms, a template language, security protections and a ready made admin site. Because so much is included, developers can move from an idea to a working site very quickly.

The other side of this is that Django has opinions. It expects your project to follow a certain structure and it names things in a certain way. Once you learn these rules, every Django project looks familiar, and that is a big help when you join a team or read someone else's code.

Django is a third party package, so you install it with pip install django. The examples in this chapter that need Django are shown for reading only. The runnable examples use the standard library to copy the ideas, such as URL matching and database access, so that you can see how the pieces work without installing anything.

What makes Django different

Flask gives you a small core and lets you choose the rest. Django gives you a large core with sensible choices already made. A new Django project already knows how to talk to a database, manage users and groups, protect against common attacks such as cross site request forgery and SQL injection, and generate an admin panel from your data. Large sites such as photo sharing and news platforms have been built with it.

Batteries included: a phrase meaning the framework ships with most of the tools a typical website needs

The MTV pattern

Django organises code into three parts called Model, Template and View, often written MTV. A model describes your data as a Python class, and each class becomes a database table. A template is an HTML file with placeholders for the data. A view is a Python function or class that receives a request, collects data from models, picks a template and returns a response. Django itself plays the role of the controller by reading the URL and choosing the view.

PartJobFile
ModelDescribes data and talks to the databasemodels.py
TemplateShows data as HTMLtemplates folder
ViewHandles the request and builds the responseviews.py
URLconfMaps URLs to viewsurls.py

Project and app structure

Django separates a project from its apps. The project is the whole website and holds the settings. An app is one feature, such as a blog, a shop or a user profile page. One project usually contains several apps, and a good app can be reused in another project. You create the project with django-admin startproject and each app with python manage.py startapp.

  • manage.py is a command line helper used to run, migrate and manage the project.
  • settings.py holds the database setting, installed apps, time zone and secret key.
  • urls.py is the table of contents of your site and maps paths to views.
  • models.py holds the classes that describe your tables.
  • admin.py registers models with the automatic admin site.

URLs and views

When a request arrives, Django walks through the list called urlpatterns and picks the first pattern that matches the path. It then calls the connected view with the request and any captured values. In modern Django you write patterns with the path() function, such as path("books/<int:book_id>/", views.book_detail). The next example is a tiny copy of this idea written with the re module, so you can see the matching steps.

Example 1: A tiny URL dispatcher
import re

def home(request):
    return "Home page"

def book_detail(request, book_id):
    return f"Book number {book_id}"

urlpatterns = [
    (r"^$", home),
    (r"^books/(?P<book_id>[0-9]+)/$", book_detail),
]

def resolve(path):
    for pattern, view in urlpatterns:
        match = re.match(pattern, path)
        if match:
            return view("request-object", **match.groupdict())
    return "404 Not Found"

for path in ["", "books/12/", "books/abc/"]:
    print(repr(path), "->", resolve(path))
'' -> Home page 'books/12/' -> Book number 12 'books/abc/' -> 404 Not Found

Models and the ORM

With the Django ORM, which means object relational mapper, you work with Python objects and Django writes the SQL for you. You write Book.objects.filter(pages__gte=200) and Django builds the matching query. When you change a model you run makemigrations, which writes a migration file describing the change, and then migrate, which applies it to the database. The next example uses sqlite3 to show the kind of work the ORM does for you.

Example 2: What an ORM does behind the scenes
import sqlite3

# What a Django model and migration do behind the scenes
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE library_book (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, pages INTEGER)")

class Book:
    table = "library_book"

    @classmethod
    def create(cls, title, pages):
        db.execute(f"INSERT INTO {cls.table} (title, pages) VALUES (?, ?)", (title, pages))

    @classmethod
    def filter_min_pages(cls, minimum):
        rows = db.execute(f"SELECT title FROM {cls.table} WHERE pages >= ? ORDER BY title", (minimum,))
        return [row[0] for row in rows]

Book.create("Python Basics", 250)
Book.create("Web Apps", 410)
Book.create("Tiny Guide", 90)
print(Book.filter_min_pages(200))
print(db.execute("SELECT COUNT(*) FROM library_book").fetchone()[0])
['Python Basics', 'Web Apps'] 3

Templates

Django templates use curly braces like {{ book.title }} to print values and {% for book in books %} to repeat parts. Templates can extend a base layout with {% extends %}, so the menu and footer are written only once. The template language is intentionally simple. Heavy logic belongs in views and models, not in templates. Django also escapes values by default to protect against script injection.

Example 3: Filling a page from a context dictionary
from string import Template

page = Template("<h1>$title</h1>\n<p>$count books</p>")

def book_list_view(request):
    context = {"title": "My Library", "count": 3}
    return page.substitute(context)

print(book_list_view(None))
<h1>My Library</h1> <p>3 books</p>

A view passes a dictionary called the context to the template. In the example above the standard library Template does the same job in a very small way.

Putting the real pieces together

The next block shows how a model, a view and a URL pattern fit together in a real Django app. It cannot run here because it needs a full Django project with settings and a database.

Example 4: Model, view and URLs in a Django app
# library/models.py
from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=200)
    pages = models.IntegerField(default=0)

    def __str__(self):
        return self.title

# library/views.py
from django.shortcuts import render
from .models import Book

def book_list(request):
    books = Book.objects.filter(pages__gte=200)
    return render(request, "library/book_list.html", {"books": books})

# library/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path("books/", views.book_list, name="book_list"),
]
No output: these files are loaded by Django when the server runs.

Commands you will use every day

Most of your work with Django happens through manage.py. The block below lists the usual order for a new project. The runserver command starts the development server, which reloads when your code changes. A site is visited at http://127.0.0.1:8000/ while the server runs.

Example 5: Starting a Django project
django-admin startproject mysite
cd mysite
python manage.py startapp library
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
python manage.py runserver
Watching for file changes with StatReloader System check identified no issues (0 silenced). Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C.

The admin site

One of the most loved parts of Django is its admin site. After you register a model in admin.py, Django builds pages to add, edit, search and delete records. You log in with the account made by createsuperuser. This is very useful for editors and for checking data while you build the real pages.

Never share the SECRET_KEY from settings.py and never leave DEBUG = True on a public server.

Python syntax

Syntax
django-admin startproject mysite
python manage.py startapp appname
Syntax
class Item(models.Model):
    name = models.CharField(max_length=100)
Syntax
path("items/<int:pk>/", views.item_detail, name="item_detail")
Syntax
def view(request):
    return render(request, "app/page.html", {"key": value})

Real-world applications

  • Content sites such as news portals and blogs
  • Online shops with accounts, carts and orders
  • Internal business tools with an admin panel
  • Social and community platforms
  • REST APIs when combined with Django REST Framework

Common mistakes

Mistake: Forgetting to add a new app to INSTALLED_APPS
Fix: Add the app name in settings.py, otherwise its models and templates are not found.
Mistake: Changing a model but not running makemigrations and migrate
Fix: Run both commands after every model change so the database matches your code.
Mistake: Putting too much logic into templates
Fix: Do the work in views or models and give the template ready to show values.
Mistake: Leaving DEBUG = True and a visible SECRET_KEY in a public project
Fix: Load secrets from environment variables and set DEBUG to False in production.
Mistake: Forgetting the csrf token in a POST form, which gives a 403 error
Fix: Add the csrf_token template tag inside every form that uses POST.

Important tips

  • Create a virtual environment before installing Django.
  • Follow the official tutorial polls project once, as it covers all the basics.
  • Use the Django shell with python manage.py shell to try queries quickly.
  • Give every URL pattern a name so you can use the url tag in templates.

Key points summary

  • Django is a full featured framework with batteries included.
  • MTV stands for Model, Template, View.
  • A project contains one or more apps.
  • The ORM lets you query a database with Python code.
  • Migrations carry model changes to the database.
  • The admin site is built automatically from registered models.

Exam and interview points

  • Django follows the MTV pattern.
  • manage.py runserver starts the development server.
  • makemigrations creates migration files and migrate applies them.
  • urlpatterns is the list of URL patterns that Django checks in order.
  • The ORM translates Python method calls into SQL.

Quick revision

  • pip install django installs the framework.
  • startproject makes the site, startapp makes a feature.
  • Model is data, Template is HTML, View is logic.
  • path() connects a URL to a view.
  • makemigrations then migrate after model edits.
  • createsuperuser gives access to the admin site.

Frequently asked questions

Should I choose Django or Flask?

Choose Django for larger data driven sites where you want users, admin and security built in. Choose Flask for small services or when you want full control over each part.

Is Django MVC?

It is close to MVC. Django calls its parts Model, Template and View, and the framework itself does the controller work of routing requests.

What is the difference between a project and an app?

A project is the whole website and its settings. An app is a feature inside the project, such as a blog.

Do I have to use the Django ORM?

No, but most people do because it saves time and keeps the code safe from SQL injection. You may also run raw SQL if you need to.

Which databases does Django support?

SQLite, PostgreSQL, MySQL and MariaDB are supported directly. SQLite is the default and needs no setup.

Practise this chapter

21 practice questions Take the chapter quiz

Related chapters