Django Highlights Summary
Every highlight bullet from the 12 pages in this section, gathered on one page and grouped by the page it came from.
- Django names its own controller layer 'View' - the MTV pattern maps loosely, not directly, onto classic MVC
- Middleware forms a nested onion: each layer wraps the next, running code both before and after the view
- QuerySets are lazy - defining one issues no SQL until it's iterated, sliced, or cast to a list or bool
- Migrations are generated diffs against tracked model state, not automatic schema sync
- select_related and prefetch_related exist specifically to counter the N+1 cost that laziness makes easy to trigger
- Apps organize features; projects hold settings and root URL routing
- Keep secrets in environment variables, never hardcode credentials
- URL path converters enforce type validation like int or uuid
- Template inheritance eliminates duplicate HTML layout code
- Middleware execution order affects CSRF token and session behavior
- Place management commands in management/commands/ for cron jobs
- ForeignKey(Author, on_delete=models.CASCADE) links related tables with automatic cleanup
- ManyToManyField handles many-to-many relationships with implicit join tables
- Use select_related() for forward foreign keys to fetch in a single query
- Use prefetch_related() for reverse relations and many-to-many to batch fetches
- Migrations codify schema changes as Python files, applied sequentially
- Add database indexes to model fields queried frequently to improve read performance
- Run makemigrations then migrate to evolve schema safely
- AddField adds new columns to models during schema evolution
- Review generated migrations in PRs before deployment
- Use data migrations to backfill existing rows safely
- Squash long migration chains to keep history manageable
- Test migrations against production-like data before live deploy
- ModelSerializer with Meta.model and fields defines the API schema
- ModelViewSet with queryset and serializer_class provides CRUD ops
- Serializers validate input and transform data to JSON output
- Routers automatically register URL patterns from viewsets
- Viewsets map HTTP verbs directly to corresponding actions
- Function views with @api_view decorator enable browsable API
- Subclass forms.Form with EmailField and CharField validators
- Instantiate forms with request.POST or None to bind POST data
- Call form.is_valid() to gate POST processing before redirecting users
- Add csrf_token to POST form templates to prevent cross-site attacks
- Re-render form in template context on validation failure to show errors
- Templates escape variables by default to prevent XSS vulnerabilities
- @login_required decorator enforces per-view login requirements on Django views
- authenticate(request, username, password) returns User if valid, None if not
- Combine model-level and custom permission checks for fine-grained access control
- Session middleware attaches request.user; manage auth state via login() and logout()
- Use argon2 or bcrypt hashers in production to secure password storage
- Group-based permissions enable role-like access patterns across views and models
- Define async views with async def to handle async-compatible database operations
- Use AsyncWebsocketConsumer in Channels for WebSocket connections
- Wrap blocking ORM calls with sync_to_async to avoid blocking async views
- Deploy async views on ASGI servers, not WSGI, for proper async support
- Enable Channels' channel layers for pub/sub messaging between consumers
- Mix sync and async views in the same Django deployment for gradual migration
- Use the admin.register decorator to quickly set up CRUD interfaces for models
- list_display and search_fields customize what fields appear and enable searching
- Admin auto-generates forms from your model definitions, no manual form code needed
- list_filter and readonly_fields control filtering and prevent accidental edits
- Lock down admin with staff-only flags and 2FA at the proxy for security
- Admin interface powers internal ops consoles and rapid model inspection
- Use @cache_page decorator on views for simple HTTP caching
- Apply prefetch_related for related querysets to prevent N+1
- Use select_related to fetch FK relationships in a single query
- prefetch_related executes separate queries but prevents N+1
- Cache backends support Redis or in-memory storage options
- Profile Django caching with Debug Toolbar during development
- Run Gunicorn with multiple workers for production WSGI applications
- Set DEBUG = False and configure ALLOWED_HOSTS for production security
- Use SECURE_PROXY_SSL_HEADER to trust reverse proxy SSL information
- Collect static files to CDN or object storage before deployment
- Run database migrations as a release step before scaling up
- Implement health check endpoints like /health for load balancers
- Keep business invariants on models or services
- Add database indexes on columns used for filtering
- Prefer class-based views and push logic to services
- Store secrets in environment variables, never in code
- Use parameterized ORM queries to prevent SQL injection
- Run all tests before running migrations in CI
49454e4f4d5f434e4f5904434556494d43451c1c1c56181a181c1a1d
Reviewed by Chris St. John·Last updated Jul 31, 2026