Django: Web Framework Fundamentals

Django is an advanced Web Framework based on Python and provides the main basic components required for Web application development, including URL Routing, Views, ORM, Authentication, Middleware, Templates and database migration.

Django follows the MTV (Model–Template–View) architecture, similar to traditional MVC:

  • Model: Responsible for data model and database interaction.
  • Template: Responsible for HTML page display.
  • View: Responsible for request processing, business logic and response generation.

For front-end and back-end separation projects, Django usually provides JSON API through Django REST Framework (DRF), and Template is used relatively rarely.

1. Django Project and App

Django uses the two-level structure Project and App to organize the code.

  • Project: Configuration and entry of the entire Django application.
  • App: Encapsulates a certain type of business function and can be multiplexed by multiple Project.

Create project

Installation:

pip install django

Create Project:

django-admin startproject config .

Create App:

python manage.py startapp users

Project structure:

project/
├── manage.py
├── config/
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   ├── asgi.py
│   └── wsgi.py
│
└── users/
    ├── __init__.py
    ├── admin.py
    ├── apps.py
    ├── models.py
    ├── views.py
    ├── tests.py
    └── migrations/

Main documents:

Filefunction
manage.pyDjango command line management entrance
settings.pyProject configuration
urls.pyURL routing entry
wsgi.pyWSGI deployment entrance
asgi.pyASGI deployment entrance
models.pydata model
views.pyRequest processing logic
apps.pyApp configuration
admin.pyDjango Admin Registration
migrations/Database migration file

Register App

After creating App, you need to register in settings.py:

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",

    "users",
]

App doesn't necessarily require a separate database table or URL, it's just a way of organizing the functionality of Django.

In actual development, it can be split according to business areas:

apps/
├── users/
├── products/
├── orders/
└── payments/

It is not recommended to create a App for every small function to avoid excessive splitting.

2. Settings: Project configuration

settings.py is the core configuration file of Django.

Common configurations:

Settingfunction
DEBUGWhether to enable debugging mode
SECRET_KEYKeys for security purposes such as cryptographic signatures
ALLOWED_HOSTSHost allowed access
INSTALLED_APPSRegistered App
MIDDLEWAREMiddleware list
ROOT_URLCONFroot routing module
DATABASESDatabase connection configuration
TEMPLATESTemplate engine configuration
STATIC_URLStatic resource URL
MEDIA_ROOTUpload file storage directory
TIME_ZONE / USE_TZTime processing settings

DATABASES

For example PostgreSQL:

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.postgresql",
        "NAME": "app_db",
        "USER": "app_user",
        "PASSWORD": "...",
        "HOST": "localhost",
        "PORT": "5432",
    }
}

Actual production environments should use environment variables or Secret to manage sensitive configurations.

Development and production environments

import os

DEBUG = os.getenv("DJANGO_DEBUG", "false").lower() == "true"

SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]

ALLOWED_HOSTS = os.getenv(
    "DJANGO_ALLOWED_HOSTS",
    "localhost,127.0.0.1",
).split(",")

Production environment should pay attention to:

  • DEBUG=False。
  • SECRET_KEY should not be submitted to Git.
  • Set ALLOWED_HOSTS correctly.
  • Configure HTTPS, secure Cookie, and trusted agents.
  • Static resources and uploaded files should have clear storage and access policies.

Settings and App Config

settings.py manages the entire Project configuration.

apps.py defines the meta-information of a certain App:

from django.apps import AppConfig

class UsersConfig(AppConfig):
    default_auto_field = "django.db.models.BigAutoField"
    name = "users"

Part of the App initialization logic can be performed through AppConfig.ready(), such as registering Signals.

However, it is not recommended to perform database queries or time-consuming tasks in ready() because application initialization may occur across multiple administrative commands and Worker processes.

3. URL Routing: Route distribution

Django uses URLconf to map URL to View.

basic routing

# config/urls.py

from django.urls import path
from users.views import get_user

urlpatterns = [
    path("users/<int:user_id>/", get_user),
]

View:

# users/views.py

from django.http import JsonResponse

def get_user(request, user_id):
    return JsonResponse({"user_id": user_id})

Request:

GET /users/123/

will call:

get_user(request, user_id=123)

Path Converters

Django built-in common path converter:

ConverterPurpose
strString not containing /
intnonnegative integer
slugSlug string
uuidUUID
pathPaths that can contain /

For example:

path("posts/<slug:slug>/", get_post)
path("files/<path:file_path>/", get_file)

include: Modular routing

Large projects often have each App manage its own routing.

# users/urls.py

from django.urls import path
from . import views

app_name = "users"

urlpatterns = [
    path("<int:user_id>/", views.get_user, name="detail"),
]

Project entrance:

# config/urls.py

from django.urls import include, path

urlpatterns = [
    path("api/users/", include("users.urls")),
]

URL Naming and reverse

URL can use names for reverse resolution to avoid hard-coding paths in business code.

from django.urls import reverse

url = reverse("users:detail", kwargs={"user_id": 123})
# "/api/users/123/"

Common methods:

  • reverse(): Generate URL based on the route name.
  • reverse_lazy(): Delayed reverse parsing, often used in class attributes or scenarios where URLconf has not yet been loaded.
  • redirect(): Redirect to URL or named route.

4. Views: Request processing logic

Django View receives HttpRequest and returns HttpResponse.

There are two main forms:

  • Function-Based Views(FBV)。
  • Class-Based Views(CBV)。

Function-Based View

from django.http import JsonResponse

def get_user(request, user_id):
    if request.method != "GET":
        return JsonResponse(
            {"error": "Method not allowed"},
            status=405,
        )

    return JsonResponse({
        "id": user_id,
        "name": "Alice",
    })

For the limit HTTP Method, it is more recommended to use Decorator:

from django.views.decorators.http import require_GET

@require_GET
def get_user(request, user_id):
    return JsonResponse({"id": user_id})

Class-Based View

Use the View class to organize the different HTTP Method:

from django.views import View
from django.http import JsonResponse

class UserView(View):
    def get(self, request, user_id):
        return JsonResponse({"id": user_id})

    def post(self, request, user_id):
        return JsonResponse(
            {"message": "Updated"},
            status=200,
        )

Route registration:

path("users/<int:user_id>/", UserView.as_view())

as_view() converts the class into View that Django can call.

Generic Class-Based Views

Django has built-in some common View:

Viewfunction
TemplateViewrender template
ListViewDisplay object list
DetailViewdisplay a single object
CreateViewCreate object
UpdateViewModify object
DeleteViewDelete object

These are mainly targeted at traditional Web development of Django Template + Form.

If it is JSON REST API, usually use APIView, GenericAPIView or ViewSet of DRF, and there is no need to mix two sets of general View systems.

5. Request and Response

HttpRequest

Django encapsulates the incoming HTTP request into a HttpRequest object.

def example(request):
    request.method
    request.path
    request.GET
    request.POST
    request.headers
    request.body
    request.COOKIES
    request.FILES
    request.user

Common properties:

Propertiesmeaning
request.methodHTTP method
request.GETQuery Parameters
request.POSTform data
request.bodyoriginal request body
request.headersHTTP Headers
request.FILESUpload files
request.COOKIESCookie
request.userCurrent authenticated user
request.sessionSession data

NOTE: request.POST is not JSON Body requested by any POST.

If the client sends JSON:

import json

def create_user(request):
    data = json.loads(request.body)

Plain Django View does not automatically complete JSON Schema verification like DRF Serializer or FastAPI Pydantic.

HttpResponse

Return text:

from django.http import HttpResponse

def hello(request):
    return HttpResponse("Hello World")

Return JSON:

from django.http import JsonResponse

def hello(request):
    return JsonResponse({
        "message": "Hello World"
    })

Common response classes:

Responsefunction
HttpResponseGeneric HTTP response
JsonResponseJSON response
HttpResponseRedirectRedirect
StreamingHttpResponseStreaming response
FileResponsefile response

render and redirect

Traditional server-side rendering:

from django.shortcuts import render, redirect

def home(request):
    return render(
        request,
        "home.html",
        {"title": "Home"},
    )

Redirect:

def go_home(request):
    return redirect("home")

Where render() will use Django Template Engine to generate HTML.

6. Middleware: Request and response processing chain

Middleware is the request handling mechanism between Web Server and View.

Commonly used for:

  • Authentication / Session。
  • CSRF Protection。
  • Security Headers。
  • CORS。
  • Logging。
  • Request Tracking。
  • Public response handling.

Request processing flow

HTTP Request
    ↓
SecurityMiddleware
    ↓
SessionMiddleware
    ↓
AuthenticationMiddleware
    ↓
Custom Middleware
    ↓
URL Routing / View
    ↓
Custom Middleware
    ↓
AuthenticationMiddleware
    ↓
SessionMiddleware
    ↓
SecurityMiddleware
    ↓
HTTP Response

What is shown here is a simplified Middleware calling relationship. The actual processing chain also involves exceptions, template response and other stages.

Requests typically go to Middleware in the configured order, with responses coming back in the opposite direction.

Custom Middleware

import time

class RequestTimingMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        start = time.perf_counter()

        response = self.get_response(request)

        elapsed = time.perf_counter() - start

        response["X-Process-Time"] = str(elapsed)

        return response

Register:

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "users.middleware.RequestTimingMiddleware",
]

NOTE: This is just a simplified configuration showing Middleware. Real projects should keep the other Middleware required by default, such as CSRF, Common and Message Middleware.

Middleware sequence

The order may affect functionality.

For example:

SessionMiddleware
    ↓
AuthenticationMiddleware

AuthenticationMiddleware relies on the information Session provided by SessionMiddleware, so it usually must be queued after it.

Middleware and Decorator

  • Middleware: Handles project-wide requests or responses.
  • Decorator: Add logic for specific View.

For example:

from django.views.decorators.cache import cache_page

@cache_page(60)
def cached_view(request):
    ...

7. Authentication: Identity authentication and authorization

Django is built into django.contrib.auth, providing:

  • User Model。
  • Password Hashing。
  • Session Authentication。
  • Login / Logout。
  • Groups。
  • Permissions。

Authentication and Authorization

  • Authentication: Determine who the user is.
  • Authorization: Determine what permissions the user has.

User authentication

from django.contrib.auth import authenticate, login

def login_user(request):
    username = request.POST.get("username")
    password = request.POST.get("password")

    user = authenticate(
        request,
        username=username,
        password=password,
    )

    if user is not None:
        login(request, user)
        return redirect("home")

    return HttpResponse("Invalid credentials", status=401)

authenticate() checks credentials and returns User or None.

login() associates the user identity to the current Session.

Here is a simplified example; an actual login to Endpoint requires the correct Method restrictions, CSRF guarding, input validation, and login failure protection.

current user

def profile(request):
    if request.user.is_authenticated:
        return JsonResponse({
            "username": request.user.get_username()
        })

    return JsonResponse(
        {"detail": "Not authenticated"},
        status=401,
    )

Unlogged users usually correspond to AnonymousUser.

login_required

from django.contrib.auth.decorators import login_required

@login_required
def profile(request):
    ...

Unauthenticated users are usually redirected to the login page.

If it is REST API, it is often necessary to return a 401/403 response suitable for API, combined with the Authentication / Permission mechanism of DRF.

Permission

Django built-in basic model permissions:

request.user.has_perm("users.change_profile")

Default model permissions include:

add
change
delete
view

Permissions can also be assigned uniformly through Group.

Session Authentication

Django defaults to the commonly used Session authentication mechanism:

Username / Password
        ↓
authenticate()
        ↓
login()
        ↓
Session Created
        ↓
Session Cookie
        ↓
Subsequent Requests
        ↓
Session + AuthenticationMiddleware
        ↓
request.user

Browsers Cookie typically store the Session identifier instead of storing the user password directly.

The Session Authentication, CSRF Protection, and Cookie security configurations of Django need to be considered together.

CSRF Protection

For authentication based on Cookie, browsers automatically ship with Cookie, so cross-site request forgery (CSRF) needs to be guarded against.

Django Built-in:

django.middleware.csrf.CsrfViewMiddleware

The HTML form is typically used:

{% csrf_token %}

The AJAX request with separate front-end and back-end needs to carry CSRF Token according to the back-end agreement.

Note: CORS and CSRF are different security mechanisms, and configuring CORS cannot replace CSRF protection.

Custom User Model

If the project may require custom user fields, username rules, or authentication structures, it is generally recommended to consider customizing User Model at the beginning of the project.

AUTH_USER_MODEL = "users.User"

Replacing User Model after there have been a large number of migrations and foreign key associations will be significantly complicated.

8. Migration: Database structure migration

Django Migration is used to manage version changes of database Schema.

For example:

# users/models.py

from django.db import models

class Profile(models.Model):
    name = models.CharField(max_length=100)
    age = models.IntegerField(null=True)

makemigrations

python manage.py makemigrations

Generate Migration files based on Model changes.

For example:

users/migrations/
├── 0001_initial.py
└── 0002_profile_age.py

migrate

python manage.py migrate

Execute Migration that has not yet been applied, making the database structure consistent with the migration state.

The difference between the two:

commandfunction
makemigrationsGenerate migration files based on Model changes
migrateApply Migration to database
showmigrationsView migration status
sqlmigrateView SQL that may be generated by the migration operation
migrate app_name 0001Migrate to a specific version

How Migration works

models.py
    ↓
makemigrations
    ↓
Migration Files
    ↓
migrate
    ↓
Database Schema

Django generates a new migration operation based on the difference between the current state of Model and the existing Migration State.

Migration files typically contain:

class Migration(migrations.Migration):
    dependencies = [
        ("users", "0001_initial"),
    ]

    operations = [
        ...
    ]
  • dependencies: Depends on other Migration.
  • operations: Schema or data operation to be performed.

Django records the applied migrations through the django_migrations table.

Schema Migration and Data Migration

Schema Migration:

CreateModel
AddField
AlterField
RemoveField

Data Migration:

Use operations such as RunPython to migrate existing data.

For example, after adding a field, fill in default business data for historical records.

Migration Notes

  • Migration files should be submitted to Git.
  • Migration files used by deployed environments should not be deleted arbitrarily.
  • Modifying Model does not mean automatically modifying the database.
  • Before migrating a production environment, backups, table lock times, and rollback capabilities should be considered.
  • Adding new fields, indexes or modification types to large data tables may bring significant database operation costs.

For complex business systems, Migration should be managed as part of the deployment process instead of manually modifying the database structure in the production environment.

9. WSGI, ASGI and Django deployment

Django supports both WSGI and ASGI deployment interfaces.

WSGI

Traditional sync Web Server Interface.

Common combinations:

Client
   ↓
Nginx
   ↓
Gunicorn
   ↓
Django WSGI
   ↓
Database

ASGI

Application interface that supports asynchronous communication.

Common combinations:

Client
   ↓
Nginx
   ↓
Uvicorn / ASGI Server
   ↓
Django ASGI
   ↓
Database

Django supports asynchronous View:

async def my_view(request):
    ...

But this does not mean that the entire Django application automatically becomes fully asynchronous.

Need to consider:

  • Middleware Whether it supports asynchronous.
  • Whether database operations use an asynchronous interface.
  • Whether there is blocking synchronization code.
  • How ASGI Server operates.

The deployment details of Gunicorn, Uvicorn, Nginx, Docker and CI/CD can be placed in independent articles, and there is no need to repeat them in the Django basics.

10. Django request life cycle

Connect the previous concepts together:

HTTP Request
    ↓
WSGI / ASGI Server
    ↓
Django Application
    ↓
Middleware
    ↓
URL Resolver
    ↓
View
    ├── Business Logic
    ├── Model / ORM
    ├── Authentication / Permissions
    └── Template / Serialization
    ↓
HttpResponse
    ↓
Middleware
    ↓
HTTP Response

There are several important boundaries that need to be understood:

  • settings.py: Determines how the framework is configured.
  • urls.py: Determines which View the request will be processed by.
  • views.py: Process requests and organize business logic.
  • models.py: Define the data model.
  • middleware: Handles common logic across View.
  • authentication: Provides user identity and permission capabilities.
  • migrations: Evolution of management database Schema.

Together these components form the basis of Django Web Application.


Summary

Knowledge pointsimportance
Project / Appcore
Settings / INSTALLED_APPScore
URL Routing / include / reversecore
FBV / CBVcore
HttpRequest / HttpResponsecore
Middleware / ordercore
Authentication / Session / Permissionscore
CSRF Protectionimportant
makemigrations / migratecore
WSGI / ASGIimportant
Template / Generic Viewson demand
Admin / Signalson demand

Django The most important concepts:

  1. Project / App: Project is responsible for the overall configuration, and App is responsible for the modular business functions.
  2. URL Routing / Views: URLconf is responsible for routing distribution, and View is responsible for processing requests and returning responses.
  3. Middleware: Implement common functions across business modules in the request and response processing chain.
  4. Authentication / Session: Django provides a mature user, session and permission system.
  5. Migration: Maintain database structure changes through versioned migration files.
  6. WSGI / ASGI: Determines how Django is integrated with the application server and affects how synchronous and asynchronous requests are handled.

For the Django project based on RESTful API, the next step should focus on mastering Django ORM and Django REST Framework, which respectively solve the problems of data access and API serialization, verification and interface organization.

Reference documentation

Back to top