Jesse A. Green / notebook

Django User Guide

Generated May 2026 from django/django at 21dcd9a

AI-generated documentation. The library is checked by sampling (three repositories so far); this guide was not individually reviewed. Verify against the project before relying on it.

1. Quick Start

Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. It handles much of the complexity of web development — URL routing, database access, templating, form handling, authentication, and administration — so you can focus on writing your application.

Key features:

  • ORM (Object-Relational Mapper) — define data models in Python and query databases without writing SQL
  • Automatic admin interface — a production-ready admin site generated from your models
  • URL routing — clean, elegant URL design with path() and re_path()
  • Template engine — a powerful, extensible template language with inheritance and filters
  • Form handling — validation, rendering, and model-backed forms out of the box
  • Authentication system — users, groups, permissions, and session management
  • Middleware framework — request/response processing pipeline (CSRF, security, caching, i18n)
  • Management commands — extensible CLI via django-admin and manage.py
  • Internationalization (i18n) — full translation and localization support
  • Background tasks — built-in async task execution framework

Prerequisites:

  • Python 3.10 or later
  • pip (Python package manager)

Quickest way to start:

pip install django
django-admin startproject mysite
cd mysite
python manage.py migrate
python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
May 06, 2026 - 00:00:00
Django version 6.1, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

Tip

Visit http://127.0.0.1:8000/ in your browser to see the Django welcome page. You now have a working project.

What to try next:

  • Create your first app: see Core Usage below
  • Set up a database: see Configuration
  • Create an admin user: see Common Tasks

2. Installation

System Requirements

Requirement Minimum Recommended
Python 3.10 3.12+
pip Any Latest
Database SQLite (built-in) PostgreSQL 14+
OS Linux, macOS, Windows Linux

Installation Methods

pip (recommended)

pip install django

pip (specific version)

pip install django==6.1

Virtual environment

python -m venv myenv
source myenv/bin/activate  # Linux/macOS
myenv\Scripts\activate     # Windows
pip install django

From source

git clone https://github.com/django/django.git
cd django
pip install -e .

Post-Install Verification

python -m django --version
6.1
django-admin --version
6.1

Important

Always use a virtual environment for Django projects to avoid dependency conflicts between projects. Never install Django globally in a production setting.

Database Driver Installation

Django includes SQLite support by default. For other databases, install the appropriate driver:

Database Driver Package Install Command
PostgreSQL psycopg or psycopg2 pip install psycopg[binary]
MySQL mysqlclient pip install mysqlclient
Oracle oracledb or cx_Oracle pip install oracledb

Optional Dependencies

Package Purpose Install
Pillow ImageField support pip install Pillow
argon2-cffi Argon2 password hashing pip install argon2-cffi
bcrypt bcrypt password hashing pip install bcrypt
pywatchman Efficient file watching for auto-reload pip install pywatchman
tblib Tracebacks in parallel test runner pip install tblib

GIS Support (GeoDjango)

GeoDjango requires additional system libraries:

Library Purpose
GEOS Geometry operations
GDAL Geospatial data abstraction
PROJ Coordinate transformations
PostGIS / SpatiaLite Spatial database extensions

Warning

GeoDjango has significant system-level dependencies (GEOS, GDAL, PROJ). Install these via your OS package manager before attempting to use django.contrib.gis.

Install Troubleshooting

Error: No module named 'django'

Cause: Django is not installed in the active Python environment.

Solution:

  1. Verify you are in the correct virtual environment
  2. Run pip install django
  3. Confirm with python -c "import django; print(django.__version__)"

Error: command not found: django-admin

Cause: The Python scripts directory is not in your PATH.

Solution:

  1. Check pip show django to find the install location
  2. Add the Scripts (Windows) or bin (Linux/macOS) directory to your PATH
  3. Alternatively, use python -m django instead

Error: django.core.exceptions.ImproperlyConfigured: Requested setting ...

Cause: The DJANGO_SETTINGS_MODULE environment variable is not set.

Solution:

export DJANGO_SETTINGS_MODULE=mysite.settings

Error: pip install mysqlclient fails with compilation errors

Cause: Missing system-level MySQL development libraries.

Solution:

# Debian/Ubuntu
sudo apt-get install python3-dev default-libmysqlclient-dev build-essential
# macOS
brew install mysql pkg-config

3. Configuration

Django uses a Python settings module for configuration. When you create a project with django-admin startproject, it generates a settings.py file with sensible defaults.

The Settings Module

Django locates your settings via the DJANGO_SETTINGS_MODULE environment variable. The generated manage.py sets this automatically:

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')

Important

The SECRET_KEY setting must not be empty. Django raises ImproperlyConfigured if it is. In production, load it from an environment variable — never commit it to version control. Keys shorter than 50 characters, with fewer than 5 unique characters, or prefixed with django-insecure- trigger security warnings.

Essential Settings

# mysite/settings.py

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'your-secret-key-here'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

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

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'mysite.urls'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

Database Configuration Examples

# PostgreSQL
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'mydatabase',
        'USER': 'myuser',
        'PASSWORD': 'mypassword',
        'HOST': 'localhost',
        'PORT': '5432',
    }
}

# MySQL
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'mydatabase',
        'USER': 'myuser',
        'PASSWORD': 'mypassword',
        'HOST': 'localhost',
        'PORT': '3306',
    }
}

Common User-Facing Settings

Setting Default Purpose
DEBUG True Enable debug mode (detailed error pages). Set to False in production.
ALLOWED_HOSTS [] List of host/domain names this site can serve. Required when DEBUG=False.
LANGUAGE_CODE 'en-us' Default language for the site
TIME_ZONE 'America/Chicago' Default time zone
USE_TZ True Use timezone-aware datetimes
STATIC_URL 'static/' URL prefix for static files
MEDIA_URL '' URL prefix for user-uploaded files
DEFAULT_AUTO_FIELD 'django.db.models.BigAutoField' Default primary key field type for models
ROOT_URLCONF — Python path to root URL configuration

Environment Variables

Variable Purpose Default
DJANGO_SETTINGS_MODULE Points to the settings module Set by manage.py
DJANGO_ALLOW_ASYNC_UNSAFE Allow sync ORM calls in async context Not set
DJANGO_RUNSERVER_HIDE_WARNING Hide unsafe-for-production warning from runserver Not set
PYTHONSTARTUP Python startup script (used by shell command) System default

Note

For the complete configuration reference with all available settings, see the Admin Guide.


4. Core Usage

Creating a Project

django-admin startproject mysite
mysite/
    manage.py
    mysite/
        __init__.py
        settings.py
        urls.py
        asgi.py
        wsgi.py

Creating an App

cd mysite
python manage.py startapp polls
polls/
    __init__.py
    admin.py
    apps.py
    migrations/
        __init__.py
    models.py
    tests.py
    views.py

Tip

After creating an app, add it to INSTALLED_APPS in settings.py. Django will not discover models, management commands, or template tags from apps not listed there.

Defining Models

Models define your data structure. Each model maps to a database table:

# polls/models.py
from django.db import models

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __str__(self):
        return self.question_text

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __str__(self):
        return self.choice_text

Common field types:

Field Purpose
CharField(max_length=N) Short text (requires max_length)
TextField() Long text
IntegerField() Integer
FloatField() Floating-point number
DecimalField(max_digits, decimal_places) Fixed-precision decimal
BooleanField() True/False
DateField() Date
DateTimeField() Date and time
EmailField() Email with validation
URLField() URL with validation
FileField(upload_to='') File upload
ImageField(upload_to='') Image upload (requires Pillow)
JSONField() JSON data
ForeignKey(Model, on_delete=) Many-to-one relationship
ManyToManyField(Model) Many-to-many relationship
OneToOneField(Model, on_delete=) One-to-one relationship
CompositePrimaryKey(field1, field2) Composite primary key
GeneratedField(expression=, output_field=) Database-computed field

Relationship on_delete options:

Option Behavior
CASCADE Delete related objects
PROTECT Prevent deletion (raises ProtectedError)
RESTRICT Prevent deletion unless cascade would also delete (raises RestrictedError)
SET_NULL Set FK to NULL (requires null=True)
SET_DEFAULT Set FK to default value
SET(value) Set FK to a specific value
DO_NOTHING Do nothing (may cause IntegrityError)
DB_CASCADE Delegate cascade to the database
DB_SET_NULL Delegate SET NULL to the database
DB_SET_DEFAULT Delegate SET DEFAULT to the database

Creating and Applying Migrations

After defining or changing models, create and apply migrations:

python manage.py makemigrations polls
Migrations for 'polls':
  polls/migrations/0001_initial.py
    - Create model Question
    - Create model Choice
python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, polls, sessions
Running migrations:
  Applying polls.0001_initial... OK

Warning

Always review generated migrations before applying them. Use python manage.py sqlmigrate polls 0001 to see the SQL that will be executed. Use --check with makemigrations in CI to catch missing migrations.

Writing Views

Function-based views:

# polls/views.py
from django.http import HttpResponse
from django.shortcuts import render, get_object_or_404
from .models import Question

def index(request):
    latest_questions = Question.objects.order_by('-pub_date')[:5]
    return render(request, 'polls/index.html', {
        'latest_questions': latest_questions,
    })

def detail(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/detail.html', {'question': question})

Class-based views:

from django.views.generic import ListView, DetailView
from .models import Question

class QuestionListView(ListView):
    model = Question
    template_name = 'polls/index.html'
    context_object_name = 'latest_questions'
    ordering = ['-pub_date']
    paginate_by = 10

class QuestionDetailView(DetailView):
    model = Question
    template_name = 'polls/detail.html'

URL Configuration

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

app_name = 'polls'
urlpatterns = [
    path('', views.index, name='index'),
    path('<int:question_id>/', views.detail, name='detail'),
]

# mysite/urls.py
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
]

URL path converters:

Converter Matches Example
str Any non-empty string (excluding /) <str:slug>
int Zero or positive integer <int:id>
slug ASCII letters, numbers, hyphens, underscores <slug:slug>
uuid UUID <uuid:pk>
path Any non-empty string (including /) <path:file_path>

Note

Use re_path() instead of path() when you need regex-based URL patterns. Custom path converters can be registered with register_converter().

Templates

Django templates use a special syntax for dynamic content:

<!-- polls/templates/polls/index.html -->
{% extends "base.html" %}

{% block content %}
<h1>Latest Questions</h1>
{% if latest_questions %}
    <ul>
    {% for question in latest_questions %}
        <li><a href="{% url 'polls:detail' question.id %}">
            {{ question.question_text }}
        </a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>No polls are available.</p>
{% endif %}
{% endblock %}

Key template constructs:

Syntax Purpose Example
{{ variable }} Output a variable {{ question.question_text }}
{% tag %} Template tag (logic) {% if user.is_authenticated %}
{{ var|filter }} Apply a filter {{ name|lower }}
{# comment #} Single-line comment {# This is a comment #}
{% extends %} Template inheritance {% extends "base.html" %}
{% block %} Define/override blocks {% block content %}...{% endblock %}
{% include %} Include another template {% include "header.html" %}
{% url %} Reverse URL resolution {% url 'polls:detail' question.id %}
{% csrf_token %} CSRF protection token Required in all POST forms
{% load %} Load template tag library {% load static %}

Forms

Basic form:

# polls/forms.py
from django import forms

class ContactForm(forms.Form):
    name = forms.CharField(max_length=100)
    email = forms.EmailField()
    message = forms.CharField(widget=forms.Textarea)

Model form (auto-generated from a model):

from django.forms import ModelForm
from .models import Question

class QuestionForm(ModelForm):
    class Meta:
        model = Question
        fields = ['question_text', 'pub_date']

Using forms in views:

def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            # Process the data
            name = form.cleaned_data['name']
            return redirect('success')
    else:
        form = ContactForm()
    return render(request, 'contact.html', {'form': form})

The Admin Site

Django generates an admin interface from your models:

# polls/admin.py
from django.contrib import admin
from .models import Question, Choice

class ChoiceInline(admin.TabularInline):
    model = Choice
    extra = 3

@admin.register(Question)
class QuestionAdmin(admin.ModelAdmin):
    list_display = ['question_text', 'pub_date']
    list_filter = ['pub_date']
    search_fields = ['question_text']
    inlines = [ChoiceInline]

Create a superuser to access the admin:

python manage.py createsuperuser

Then visit http://127.0.0.1:8000/admin/ and log in.

QuerySet API (Database Queries)

# Get all objects
Question.objects.all()

# Filter
Question.objects.filter(pub_date__year=2026)

# Exclude
Question.objects.exclude(question_text__startswith='Why')

# Get single object
Question.objects.get(pk=1)

# Order
Question.objects.order_by('-pub_date')

# Limit
Question.objects.all()[:5]

# Count
Question.objects.count()

# Exists
Question.objects.filter(pub_date__year=2026).exists()

# Aggregate
from django.db.models import Avg, Count, Max, Min, Sum
Question.objects.aggregate(Avg('choice__votes'))

# Annotate
Question.objects.annotate(num_choices=Count('choice'))

# Values
Question.objects.values('question_text', 'pub_date')

# Create
q = Question.objects.create(question_text='What?', pub_date=timezone.now())

# Update
Question.objects.filter(pk=1).update(question_text='Updated?')

# Delete
Question.objects.filter(pub_date__year=2020).delete()

# Select related (FK joins)
Choice.objects.select_related('question')

# Prefetch related (M2M, reverse FK)
Question.objects.prefetch_related('choice_set')

Common field lookups:

Lookup SQL Equivalent Example
exact = name__exact='Django'
iexact ILIKE name__iexact='django'
contains LIKE '%...%' name__contains='ang'
icontains ILIKE '%...%' name__icontains='ang'
startswith LIKE '...%' name__startswith='Dj'
endswith LIKE '%...' name__endswith='go'
in IN (...) id__in=[1, 2, 3]
gt / gte > / >= votes__gt=5
lt / lte < / <= votes__lt=10
range BETWEEN pub_date__range=(start, end)
isnull IS NULL email__isnull=True
year / month / day Extract date part pub_date__year=2026
regex / iregex REGEXP name__regex=r'^D'

Tip

Chain QuerySet methods for complex queries. QuerySets are lazy — they don't hit the database until evaluated (iteration, slicing, len(), list(), bool()).

Async Support

Django provides async versions of key functions:

# Async view
async def async_index(request):
    questions = [q async for q in Question.objects.order_by('-pub_date')[:5]]
    return render(request, 'polls/index.html', {'latest_questions': questions})

# Async shortcuts
from django.shortcuts import aget_object_or_404, aget_list_or_404
question = await aget_object_or_404(Question, pk=question_id)

Warning

Calling synchronous ORM methods from an async context raises SynchronousOnlyOperation unless DJANGO_ALLOW_ASYNC_UNSAFE is set. Use async QuerySet methods (prefixed with a — aget(), acreate(), afilter(), etc.) or wrap sync calls with sync_to_async().


5. Common Tasks

Task 1: Set Up a New Project with PostgreSQL

Goal: Create a Django project backed by PostgreSQL.

Prerequisites: PostgreSQL installed, a database created.

Steps:

  1. Create and activate a virtual environment:

    python -m venv myenv && source myenv/bin/activate
    
  2. Install Django and the PostgreSQL driver:

    pip install django psycopg[binary]
    
  3. Create the project:

    django-admin startproject myproject
    
  4. Edit myproject/settings.py:

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql',
            'NAME': 'mydb',
            'USER': 'myuser',
            'PASSWORD': 'mypassword',
            'HOST': 'localhost',
            'PORT': '5432',
        }
    }
    
  5. Apply initial migrations:

    python manage.py migrate
    

Verify: python manage.py dbshell opens a PostgreSQL prompt.

Task 2: Create a REST API Endpoint

Goal: Add a JSON API endpoint to return data.

Steps:

  1. Create a view that returns JSON:

    from django.http import JsonResponse
    from .models import Question
    
    def api_questions(request):
        questions = list(
            Question.objects.values('id', 'question_text', 'pub_date')
        )
        return JsonResponse({'questions': questions})
    
  2. Add the URL:

    path('api/questions/', views.api_questions, name='api-questions'),
    

Verify: curl http://localhost:8000/api/questions/ returns JSON.

Task 3: Add User Authentication

Goal: Add login, logout, and registration.

Steps:

  1. Include auth URLs in your project:

    # mysite/urls.py
    urlpatterns = [
        path('accounts/', include('django.contrib.auth.urls')),
    ]
    
  2. Create login template at templates/registration/login.html:

    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Log in</button>
    </form>
    
  3. Set login redirect:

    # settings.py
    LOGIN_REDIRECT_URL = '/'
    
  4. Protect views with @login_required:

    from django.contrib.auth.decorators import login_required
    
    @login_required
    def dashboard(request):
        return render(request, 'dashboard.html')
    

Verify: Visit /accounts/login/ and log in with a superuser account.

Task 4: Serve Static Files

Goal: Configure and serve CSS, JavaScript, and images.

Steps:

  1. Ensure django.contrib.staticfiles is in INSTALLED_APPS

  2. Set the static URL in settings:

    STATIC_URL = 'static/'
    
  3. Place files in your app's static/ directory:

    polls/
        static/
            polls/
                style.css
    
  4. Use in templates:

    {% load static %}
    <link rel="stylesheet" href="{% static 'polls/style.css' %}">
    
  5. For production, collect all static files:

    python manage.py collectstatic
    

Task 5: Add Internationalization (i18n)

Goal: Make your app translatable.

Steps:

  1. Mark strings for translation in Python:

    from django.utils.translation import gettext_lazy as _
    
    class Question(models.Model):
        question_text = models.CharField(_('question text'), max_length=200)
    
  2. Mark strings in templates:

    {% load i18n %}
    <h1>{% trans "Latest Questions" %}</h1>
    
  3. Generate message files:

    python manage.py makemessages -l es
    
  4. Translate strings in locale/es/LC_MESSAGES/django.po

  5. Compile messages:

    python manage.py compilemessages
    

Task 6: Export and Import Data (Fixtures)

Goal: Dump data from one database and load it into another.

Steps:

  1. Export data:

    python manage.py dumpdata polls --indent 2 -o polls_data.json
    
  2. Import data:

    python manage.py loaddata polls_data.json
    

Tip

Use --natural-foreign and --natural-primary flags with dumpdata when exporting data that will be loaded into a database with different primary key sequences.

Task 7: Use the Django Shell

Goal: Interactively explore your data.

python manage.py shell
>>> from polls.models import Question
>>> from django.utils import timezone
>>> q = Question(question_text="What's new?", pub_date=timezone.now())
>>> q.save()
>>> Question.objects.all()
<QuerySet [<Question: What's new?>]>

Tip

Use --interface ipython or --interface bpython for an enhanced shell experience with tab completion and syntax highlighting. The --no-startup flag skips your PYTHONSTARTUP script.

Task 8: Write and Run Tests

Goal: Write tests and run them.

# polls/tests.py
from django.test import TestCase
from django.utils import timezone
from .models import Question

class QuestionModelTests(TestCase):
    def test_was_published_recently(self):
        time = timezone.now()
        question = Question(pub_date=time)
        self.assertIs(question.pub_date, time)
python manage.py test polls
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK
Destroying test database for alias 'default'...

Task 9: Send Test Emails

Goal: Verify email configuration.

python manage.py sendtestemail [email removed]
# Send to ADMINS and MANAGERS
python manage.py sendtestemail --admins --managers

Task 10: Inspect an Existing Database

Goal: Generate Django models from an existing database.

python manage.py inspectdb > models.py
# Inspect specific tables
python manage.py inspectdb auth_user auth_group

Note

Generated models may need manual adjustment — review field types, Meta options, and relationships. Use --include-views to also inspect database views.

Task 11: Squash Migrations

Goal: Reduce migration history for cleaner deployments.

python manage.py squashmigrations polls 0001 0010

This creates a single optimized migration replacing 0001 through 0010.

Task 12: Use Background Tasks

Goal: Run functions asynchronously using Django's built-in task framework.

from django.tasks import task

@task()
def send_welcome_email(user_id):
    # Long-running task
    user = User.objects.get(pk=user_id)
    send_email(user.email, "Welcome!")

# Enqueue the task
result = send_welcome_email.enqueue(user_id=42)

Configure a task backend in settings:

TASKS = {
    'default': {
        'BACKEND': 'django.tasks.backends.immediate.ImmediateBackend',
    }
}

6. Troubleshooting

Diagnostic Decision Tree

Problem with Django?
├── Import/startup error?
│   ├── "No module named 'django'" → Install Django in active venv
│   ├── "ImproperlyConfigured" → Check DJANGO_SETTINGS_MODULE
│   └── "AppRegistryNotReady" → Call django.setup() before accessing models
├── Database error?
│   ├── "no such table" → Run python manage.py migrate
│   ├── "relation does not exist" → Run migrations, check database name
│   └── Connection refused → Check database host/port/credentials
├── Template error?
│   ├── "TemplateDoesNotExist" → Check TEMPLATES dirs and app template dirs
│   └── "TemplateSyntaxError" → Check tag/filter syntax, {% load %} statements
├── URL error?
│   ├── 404 → Check urlpatterns, trailing slashes, APPEND_SLASH
│   └── "NoReverseMatch" → Check URL name, arguments, app_name
├── Static files not loading?
│   ├── In development → Check STATIC_URL and app static/ dirs
│   └── In production → Run collectstatic, configure web server
└── CSRF error?
    ├── Missing {% csrf_token %} in form
    └── Check CSRF_TRUSTED_ORIGINS for cross-origin requests

Error: OperationalError: no such table

Cause: Database tables have not been created for your models.

Solution:

  1. Run python manage.py makemigrations
  2. Run python manage.py migrate

Prevention: Always run migrations after adding or changing models.

Error: TemplateDoesNotExist at /

Cause: Django cannot find the specified template file.

Solution:

  1. Verify the template file exists in app/templates/app/template_name.html
  2. Check that the app is in INSTALLED_APPS
  3. Check TEMPLATES configuration in settings.py — ensure APP_DIRS is True

Error: Forbidden (403) CSRF verification failed

Cause: Missing or invalid CSRF token in a POST request.

Solution:

  1. Add {% csrf_token %} inside every <form method="post"> tag
  2. For AJAX requests, include the CSRF token in the X-CSRFToken header
  3. For cross-origin requests, add the origin to CSRF_TRUSTED_ORIGINS

Prevention: Always include {% csrf_token %} in POST forms.

Warning

Never disable CSRF protection globally. If you need to exempt a specific view, use @csrf_exempt — but understand the security implications.

Error: DisallowedHost at /

Cause: The Host header does not match any entry in ALLOWED_HOSTS.

Solution:

ALLOWED_HOSTS = ['yourdomain.com', 'www.yourdomain.com', 'localhost']

Error: ValueError: Missing staticfiles manifest entry

Cause: Using ManifestStaticFilesStorage but collectstatic has not been run.

Solution:

python manage.py collectstatic

Error: django.db.utils.IntegrityError: UNIQUE constraint failed

Cause: Attempting to insert a duplicate value in a unique column.

Solution:

  1. Use get_or_create() or update_or_create() instead of create()
  2. Handle the exception with a try/except block

Error: SynchronousOnlyOperation

Cause: Calling synchronous ORM code from an async context.

Solution:

  1. Use async QuerySet methods: await Model.objects.aget(pk=1)
  2. Or wrap with sync_to_async: await sync_to_async(Model.objects.get)(pk=1)
  3. For debugging, set DJANGO_ALLOW_ASYNC_UNSAFE=true (development only)

Caution

Setting DJANGO_ALLOW_ASYNC_UNSAFE in production can lead to data corruption under concurrent requests. Only use it for debugging or in the shell.

Error: CommandError: Conflicting migrations detected

Cause: Two developers created migrations for the same app independently.

Solution:

python manage.py makemigrations --merge

Error: ImproperlyConfigured: The SECRET_KEY setting must not be empty

Cause: SECRET_KEY is not set in settings.

Solution: Set a strong, unique SECRET_KEY in your settings or environment:

import os
SECRET_KEY = os.environ['DJANGO_SECRET_KEY']

Error: ProgrammingError: relation "django_session" does not exist

Cause: The sessions table hasn't been created.

Solution:

python manage.py migrate sessions

Error: No installed app with label 'myapp'

Cause: The app is not listed in INSTALLED_APPS.

Solution: Add the app or its AppConfig to INSTALLED_APPS:

INSTALLED_APPS = [
    # ...
    'myapp',  # or 'myapp.apps.MyappConfig'
]

7. FAQ

General

Q: What Python versions does Django 6.1 support?

Django 6.1 requires Python 3.10 or later.

Q: What databases does Django support?

Django officially supports PostgreSQL, MySQL, SQLite, and Oracle. SQLite is included with Python and requires no additional setup. Third-party backends exist for other databases.

Q: How do I check which Django version I have installed?

python -m django --version

Or in Python:

import django
print(django.VERSION)

Django 6.1 reports VERSION = (6, 1, 0, 'alpha', 0).

Q: What is the difference between django-admin and manage.py?

Both invoke the same management command system. manage.py is project-specific — it sets DJANGO_SETTINGS_MODULE for your project automatically. django-admin requires you to set the environment variable manually or pass --settings. Use manage.py inside a project; use django-admin for project-independent commands like startproject.

Q: Can I use Django with async/await?

Yes. Django supports ASGI deployment, async views, async middleware, and async ORM operations. Use get_asgi_application() in your ASGI config and deploy with an ASGI server like Daphne, Uvicorn, or Hypercorn.

Models & Database

Q: How do I reset my database?

python manage.py flush

This deletes all data but keeps the tables. To completely recreate tables, delete the database file (SQLite) or drop and recreate the database, then run python manage.py migrate.

Q: How do I add a field to an existing model?

  1. Add the field to the model class
  2. Run python manage.py makemigrations
  3. Run python manage.py migrate

For non-nullable fields, Django will ask for a default value during makemigrations.

Q: How do I use multiple databases?

Configure them in DATABASES and use a database router:

DATABASES = {
    'default': { ... },
    'analytics': { ... },
}

Use using='analytics' in queries: Model.objects.using('analytics').all()

Q: What is select_related vs prefetch_related?

select_related uses SQL JOINs for ForeignKey and OneToOneField — one query, best for single-valued relationships. prefetch_related uses separate queries for ManyToManyField and reverse relations — better for multi-valued relationships.

Admin

Q: How do I customize the admin site title?

admin.site.site_header = "My Site Admin"
admin.site.site_title = "My Site"
admin.site.index_title = "Dashboard"

Q: How do I make a model field read-only in admin?

class MyModelAdmin(admin.ModelAdmin):
    readonly_fields = ['created_at', 'updated_at']

Security

Q: How do I generate a new SECRET_KEY?

from django.core.management.utils import get_random_secret_key
print(get_random_secret_key())

Q: How do I protect against XSS?

Django's template engine auto-escapes HTML by default. Use {{ variable }} (not {{ variable|safe }}) unless you explicitly trust the content.

Q: How do I set up HTTPS?

Configure your web server (Nginx/Apache) for SSL, then set these in settings.py:

SECURE_SSL_REDIRECT = True
SECURE_HSTS_SECONDS = 31536000
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True

Performance

Q: How do I enable caching?

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache',
        'LOCATION': '127.0.0.1:11211',
    }
}

Use the cache_page decorator for view-level caching:

from django.views.decorators.cache import cache_page

@cache_page(60 * 15)  # Cache for 15 minutes
def my_view(request):
    ...

Q: How do I see the SQL Django generates?

# In the shell
qs = Question.objects.filter(pub_date__year=2026)
print(qs.query)

Or enable query logging:

LOGGING = {
    'loggers': {
        'django.db.backends': {
            'level': 'DEBUG',
        },
    },
}

Management Command Reference

Django includes the following built-in management commands. All are invoked via python manage.py <command> or django-admin <command>.

Core Commands

Command Purpose
check Run system checks for common problems
compilemessages Compile .po files to .mo for i18n
createcachetable Create database cache tables
dbshell Open the database client shell
diffsettings Show differences from default settings
dumpdata Export data as serialized fixtures (JSON/XML/YAML)
flush Delete all data from the database
inspectdb Generate models from an existing database
loaddata Load fixture data into the database
makemessages Extract translatable strings into .po files
makemigrations Create new migrations from model changes
migrate Apply or unapply migrations
optimizemigration Optimize a migration's operations
runserver Start the development server
sendtestemail Send a test email to verify email configuration
shell Start an interactive Python shell with Django context
showmigrations List migrations and their status
sqlflush Print the SQL for flushing the database
sqlmigrate Print the SQL for a migration
sqlsequencereset Print SQL to reset sequences
squashmigrations Squash a range of migrations into one
startapp Create a new Django app
startproject Create a new Django project
test Run tests
testserver Run a development server with test fixtures

Contrib Commands

Command App Purpose
changepassword auth Change a user's password
createsuperuser auth Create an admin superuser
collectstatic staticfiles Collect static files into STATIC_ROOT
findstatic staticfiles Find the location of a static file
remove_stale_contenttypes contenttypes Remove orphaned content types
clearsessions sessions Clear expired sessions
ogrinspect gis Generate a model from an OGR data source

Common Command Flags

Flag Commands Purpose
--database migrate, dbshell, dumpdata, loaddata, flush Specify which database to use
--noinput / --no-input migrate, flush, createsuperuser Suppress interactive prompts
--verbosity {0,1,2,3} All Control output verbosity
--settings All Specify the settings module
--pythonpath All Add a directory to the Python path
--dry-run makemigrations, collectstatic Show what would be done without doing it
--check makemigrations, migrate Exit with non-zero status if changes/unapplied migrations exist
--fake migrate Mark migrations as applied without running them