Intermediate Chapter 178 · 40 min read · Module 14: Advanced Application Development
Django Fundamentals
- 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.
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.
| Part | Job | File |
|---|---|---|
| Model | Describes data and talks to the database | models.py |
| Template | Shows data as HTML | templates folder |
| View | Handles the request and builds the response | views.py |
| URLconf | Maps URLs to views | urls.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.pyis a command line helper used to run, migrate and manage the project.settings.pyholds the database setting, installed apps, time zone and secret key.urls.pyis the table of contents of your site and maps paths to views.models.pyholds the classes that describe your tables.admin.pyregisters 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.
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))
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.
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])
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.
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))
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.
# 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"),
]
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.
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 runserverThe 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.
Python syntax
django-admin startproject mysite
python manage.py startapp appnameclass Item(models.Model):
name = models.CharField(max_length=100)path("items/<int:pk>/", views.item_detail, name="item_detail")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
Fix: Add the app name in settings.py, otherwise its models and templates are not found.
Fix: Run both commands after every model change so the database matches your code.
Fix: Do the work in views or models and give the template ready to show values.
Fix: Load secrets from environment variables and set DEBUG to False in production.
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