Public Wiki86,701View on GitHub
Want django/django knowledge in your AI?

django

Django is a high-level Python web framework that provides a complete toolkit for building web applications. It includes an ORM for database operations, a template engine for rendering HTML, URL routing, form handling, authentication, an automatic admin interface, and internationalization support. This is the core Django framework source code itself, not an application built with Django.

Tech Stack

PostgreSQLRedisExpress.js

Key Features

  • Database ORM
  • Automatic Admin Interface
  • Authentication System
  • Template Engine
  • Form Handling
  • URL Routing
  • Database Migrations
  • GIS Support
  • Caching Framework
  • Session Management

Entry Points

Start here when working with this codebase

Django Package Init
django/__init__.py

Initialize Django framework, expose version info, and provide setup() function

Start here when understanding Django initialization or modifying framework bootstrap

Django CLI Entry
django/__main__.py

Bootstrap Django's command-line interface when running python -m django

Start here when modifying CLI behavior or adding new management commands

App Registry
django/apps/registry.py

Manage lifecycle and state of Django applications and their models

Start here when modifying app loading, model registration, or app configuration

URL Routing
django/urls/__init__.py

URL routing, resolution, and path converters

Start here when adding URL patterns, path converters, or modifying routing behavior

Test Runner
tests/runtests.py

Execute Django's test suite with configurable options

Start here when running tests, adding test configurations, or debugging test failures

Shortcuts Module
django/shortcuts.py

Convenient wrapper functions for common Django operations (render, redirect, get_object_or_404)

Start here when adding new convenience functions or understanding common patterns

How to Make Changes

Common modification patterns for this codebase

Add a new API endpoint/view

1
django/views/generic/base.py

Study the View and TemplateView classes to understand the base view pattern

Pattern: See how View.dispatch() routes HTTP methods to handler methods (get, post, etc.)

2
django/views/generic/edit.py

Create your view class inheriting from appropriate base (FormView, CreateView, etc.)

Pattern: Follow FormMixin pattern for form handling, see CreateView for model creation

3
django/urls/resolvers.py

Register URL pattern using path() or re_path() in your urls.py

Pattern: See URLPattern and URLResolver classes for how patterns are matched

4
tests/generic_views/test_base.py

Add tests for your new view

Pattern: Follow ViewTest class structure with setUp and test methods

Conventions to follow:

Views should inherit from django.views.generic.View or its subclassesUse mixins for shared functionality (LoginRequiredMixin, PermissionRequiredMixin)HTTP method handlers should be lowercase (get, post, put, delete)Return HttpResponse or subclass from all view methods

Add a new model field type

1
django/db/models/fields/__init__.py

Study existing field classes like CharField, IntegerField to understand the Field base class

Pattern: See how CharField implements get_prep_value(), from_db_value(), and formfield()

2
django/db/models/fields/__init__.py

Create your new field class inheriting from Field or appropriate subclass

Pattern: Follow JSONField in django/db/models/fields/json.py for complex field example

3
django/db/backends/base/operations.py

Add database-specific operations if needed

Pattern: See how adapt_datefield_value() handles date conversion per backend

4
django/forms/fields.py

Create corresponding form field if needed

Pattern: See how CharField form field maps to models.CharField

5
tests/model_fields/test_jsonfield.py

Add comprehensive tests for your field

Pattern: Follow JSONFieldTests structure with serialization, validation, and query tests

Conventions to follow:

Fields must implement deconstruct() for migrations supportOverride get_internal_type() to map to database column typeImplement formfield() to return appropriate form fieldAdd field to django/db/models/__init__.py __all__ for public API

Add a new management command

1
django/core/management/base.py

Study BaseCommand class to understand command structure

Pattern: See how handle() method is the main entry point, add_arguments() for CLI args

2
django/core/management/commands/migrate.py

Create your command file in management/commands/ directory

Pattern: Follow migrate.py for complex command with multiple options and database operations

3
django/core/management/commands/shell.py

Reference simpler command for basic structure

Pattern: See shell.py for command with optional arguments and interactive behavior

4
tests/admin_scripts/tests.py

Add tests for your command

Pattern: See AdminScriptTestCase for testing management commands with call_command()

Conventions to follow:

Command file must be named after the command (e.g., mycommand.py for 'manage.py mycommand')Class must be named 'Command' and inherit from BaseCommandUse self.stdout.write() for output, not print()Use self.style.SUCCESS/ERROR/WARNING for colored output

Add a new middleware

1
django/middleware/common.py

Study CommonMiddleware to understand middleware structure

Pattern: See __init__(get_response), __call__(request) pattern for new-style middleware

2
django/middleware/csrf.py

Create your middleware class with process_request/process_response hooks

Pattern: See CsrfViewMiddleware for middleware that modifies both request and response

3
django/middleware/security.py

Reference SecurityMiddleware for header manipulation patterns

Pattern: See how settings are read and headers are added to response

4
tests/middleware/tests.py

Add tests for your middleware

Pattern: Follow CommonMiddlewareTest with RequestFactory for isolated testing

Conventions to follow:

Use new-style middleware with __init__(get_response) and __call__(request)Return None from process_request to continue chain, or HttpResponse to short-circuitAdd to MIDDLEWARE setting in global_settings.py if it should be defaultDocument middleware order dependencies

Add a new template tag or filter

1
django/template/defaulttags.py

Study existing tags like @register.simple_tag and @register.inclusion_tag

Pattern: See do_if() for complex tag with NodeList, cycle() for simple tag

2
django/template/defaultfilters.py

Study existing filters for filter patterns

Pattern: See @register.filter decorator usage, stringfilter for string-only filters

3
django/template/library.py

Understand Library class for registration

Pattern: See simple_tag(), inclusion_tag(), filter() methods for registration patterns

4
tests/template_tests/filter_tests/test_default.py

Add tests for your tag/filter

Pattern: Follow DefaultTests structure with setup_engine and test methods

Conventions to follow:

Use @register.simple_tag for tags that return a valueUse @register.inclusion_tag for tags that render a templateUse @register.filter for filters, add is_safe=True if output is safe HTMLCustom tags go in app's templatetags/ directory with __init__.py

Add a new contrib app

1
django/contrib/auth/__init__.py

Study auth app structure as reference for contrib app layout

Pattern: See how __init__.py exposes public API and default_app_config

2
django/contrib/auth/apps.py

Create AppConfig class for your app

Pattern: See AuthConfig for app configuration with signals and checks

3
django/contrib/auth/models.py

Create models for your app

Pattern: See User, Group, Permission models for standard model patterns

4
django/contrib/auth/admin.py

Create admin configuration if applicable

Pattern: See UserAdmin for complex admin with custom forms and fieldsets

5
tests/auth_tests/__init__.py

Create test package for your app

Pattern: Follow auth_tests structure with separate test files per feature

Conventions to follow:

Contrib apps must have apps.py with AppConfig subclassUse default_app_config in __init__.py for backwards compatibilityInclude migrations/ directory with __init__.pyAdd app to INSTALLED_APPS in tests/test_sqlite.py for test discovery

Add a new database backend feature

1
django/db/backends/base/base.py

Study DatabaseWrapper base class for backend structure

Pattern: See how connection, cursor, and transaction methods are organized

2
django/db/backends/base/operations.py

Add operation method to BaseDatabaseOperations

Pattern: See date_extract_sql(), datetime_cast_date_sql() for SQL generation patterns

3
django/db/backends/postgresql/operations.py

Implement backend-specific version in each backend

Pattern: See how PostgreSQL overrides base methods with pg-specific SQL

4
django/db/backends/base/features.py

Add feature flag if needed

Pattern: See supports_json_field, can_introspect_json_field for feature detection

5
tests/backends/tests.py

Add tests for your backend feature

Pattern: Follow BackendTestCase with skipUnlessDBFeature decorators

Conventions to follow:

Base implementation goes in django/db/backends/base/Each backend overrides in its own operations.py or features.pyUse feature flags for optional capabilitiesTest with multiple database backends using skipUnlessDBFeature

Add a new form widget

1
django/forms/widgets.py

Study existing widgets like TextInput, Select to understand Widget base class

Pattern: See how render(), get_context(), value_from_datadict() work together

2
django/forms/widgets.py

Create your widget class inheriting from Widget or appropriate subclass

Pattern: Follow SelectDateWidget for complex multi-widget example

3
django/forms/templates/django/forms/widgets/

Create template for your widget

Pattern: See input.html, select.html for widget template structure

4
tests/forms_tests/widget_tests/test_select.py

Add tests for your widget

Pattern: Follow SelectTest structure with render and value extraction tests

Conventions to follow:

Widgets must implement render() returning safe HTML stringUse template_name attribute for template-based renderingImplement value_from_datadict() for form data extractionAdd Media class for CSS/JS dependencies

Coding Conventions

Standards and patterns used in this codebase

Code Structure

Use __all__ to explicitly define public API exports in module __init__.py files

__all__ = [ "ObjectDoesNotExist", "EmptyResultSet", "FieldDoesNotExist", ]
django/core/exceptions.pydjango/shortcuts.py
Code Structure

Implement lazy module loading using __getattr__ for optional dependencies to avoid import errors

def __getattr__(name): if name == "FORMS_URLFIELD_ASSUME_HTTPS": warnings.warn(FORMS_URLFIELD_ASSUME_HTTPS_DEPRECATED_MSG, RemovedInDjango60Warning) return True raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
django/__init__.py
Documentation

Use Sphinx-style docstrings with parameter descriptions and return types for public functions

def get_object_or_404(klass, *args, **kwargs): """ Use get() to return an object, or raise an Http404 exception if the object does not exist. klass may be a Model, Manager, or QuerySet object. All other passed arguments and keyword arguments are used in the get() query. """
django/shortcuts.py
Error Handling

Define custom exception classes that inherit from appropriate base exceptions with silent_variable_failure attribute for template rendering

class ObjectDoesNotExist(Exception): """The requested object does not exist""" silent_variable_failure = True
django/core/exceptions.py
Deprecation

Use RemovedInDjangoXXWarning classes with warnings.warn() for deprecation notices, following a two-version deprecation cycle

warnings.warn(FORMS_URLFIELD_ASSUME_HTTPS_DEPRECATED_MSG, RemovedInDjango60Warning)
django/__init__.py
Testing

Use argparse with subparsers for complex CLI tools and management commands

parser = ArgumentParser(description="Manage translations") subparsers = parser.add_subparsers(dest="cmd") subparsers.add_parser("update", help="Update catalogs") subparsers.add_parser("stats", help="Generate statistics")
scripts/manage_translations.pytests/runtests.py
JavaScript

Use ESLint with specific globals configuration for Django admin JavaScript (django, jQuery, etc.)

globals: { django: "readonly", jQuery: "readonly", grp: "readonly", }
eslint.config.mjs
Version Management

Define version as a tuple (major, minor, micro, releaselevel, serial) with get_version() function for string representation

VERSION = (5, 2, 0, "alpha", 0) def get_version(version=None): "Return a PEP 440-compliant version number"
django/__init__.py
Module Entry Points

Provide __main__.py for packages that should be executable via python -m

if __name__ == "__main__": management.execute_from_command_line()
django/__main__.py
Configuration

Use settings module pattern with DJANGO_SETTINGS_MODULE environment variable for configuration

def setup(set_prefix=True): from django.conf import settings configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) apps.populate(settings.INSTALLED_APPS)
django/__init__.py
Script Organization

Place utility scripts in a dedicated scripts/ directory with clear single-purpose functionality

scripts/manage_translations.py, scripts/check_migrations.py, scripts/do_django_release.py
scripts/manage_translations.pyscripts/check_migrations.py
Import Organization

Group imports in order: standard library, third-party, local Django imports, with blank lines between groups

import functools import warnings from django.http import ( Http404, HttpResponse, ) from django.template import loader
django/shortcuts.py