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
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/__init__.pyInitialize Django framework, expose version info, and provide setup() function
Start here when understanding Django initialization or modifying framework bootstrap
django/__main__.pyBootstrap Django's command-line interface when running python -m django
Start here when modifying CLI behavior or adding new management commands
django/apps/registry.pyManage lifecycle and state of Django applications and their models
Start here when modifying app loading, model registration, or app configuration
django/urls/__init__.pyURL routing, resolution, and path converters
Start here when adding URL patterns, path converters, or modifying routing behavior
tests/runtests.pyExecute Django's test suite with configurable options
Start here when running tests, adding test configurations, or debugging test failures
django/shortcuts.pyConvenient 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
django/views/generic/base.pyStudy 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.)
django/views/generic/edit.pyCreate your view class inheriting from appropriate base (FormView, CreateView, etc.)
Pattern: Follow FormMixin pattern for form handling, see CreateView for model creation
django/urls/resolvers.pyRegister URL pattern using path() or re_path() in your urls.py
Pattern: See URLPattern and URLResolver classes for how patterns are matched
tests/generic_views/test_base.pyAdd tests for your new view
Pattern: Follow ViewTest class structure with setUp and test methods
Conventions to follow:
Add a new model field type
django/db/models/fields/__init__.pyStudy 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()
django/db/models/fields/__init__.pyCreate your new field class inheriting from Field or appropriate subclass
Pattern: Follow JSONField in django/db/models/fields/json.py for complex field example
django/db/backends/base/operations.pyAdd database-specific operations if needed
Pattern: See how adapt_datefield_value() handles date conversion per backend
django/forms/fields.pyCreate corresponding form field if needed
Pattern: See how CharField form field maps to models.CharField
tests/model_fields/test_jsonfield.pyAdd comprehensive tests for your field
Pattern: Follow JSONFieldTests structure with serialization, validation, and query tests
Conventions to follow:
Add a new management command
django/core/management/base.pyStudy BaseCommand class to understand command structure
Pattern: See how handle() method is the main entry point, add_arguments() for CLI args
django/core/management/commands/migrate.pyCreate your command file in management/commands/ directory
Pattern: Follow migrate.py for complex command with multiple options and database operations
django/core/management/commands/shell.pyReference simpler command for basic structure
Pattern: See shell.py for command with optional arguments and interactive behavior
tests/admin_scripts/tests.pyAdd tests for your command
Pattern: See AdminScriptTestCase for testing management commands with call_command()
Conventions to follow:
Add a new middleware
django/middleware/common.pyStudy CommonMiddleware to understand middleware structure
Pattern: See __init__(get_response), __call__(request) pattern for new-style middleware
django/middleware/csrf.pyCreate your middleware class with process_request/process_response hooks
Pattern: See CsrfViewMiddleware for middleware that modifies both request and response
django/middleware/security.pyReference SecurityMiddleware for header manipulation patterns
Pattern: See how settings are read and headers are added to response
tests/middleware/tests.pyAdd tests for your middleware
Pattern: Follow CommonMiddlewareTest with RequestFactory for isolated testing
Conventions to follow:
Add a new template tag or filter
django/template/defaulttags.pyStudy existing tags like @register.simple_tag and @register.inclusion_tag
Pattern: See do_if() for complex tag with NodeList, cycle() for simple tag
django/template/defaultfilters.pyStudy existing filters for filter patterns
Pattern: See @register.filter decorator usage, stringfilter for string-only filters
django/template/library.pyUnderstand Library class for registration
Pattern: See simple_tag(), inclusion_tag(), filter() methods for registration patterns
tests/template_tests/filter_tests/test_default.pyAdd tests for your tag/filter
Pattern: Follow DefaultTests structure with setup_engine and test methods
Conventions to follow:
Add a new contrib app
django/contrib/auth/__init__.pyStudy auth app structure as reference for contrib app layout
Pattern: See how __init__.py exposes public API and default_app_config
django/contrib/auth/apps.pyCreate AppConfig class for your app
Pattern: See AuthConfig for app configuration with signals and checks
django/contrib/auth/models.pyCreate models for your app
Pattern: See User, Group, Permission models for standard model patterns
django/contrib/auth/admin.pyCreate admin configuration if applicable
Pattern: See UserAdmin for complex admin with custom forms and fieldsets
tests/auth_tests/__init__.pyCreate test package for your app
Pattern: Follow auth_tests structure with separate test files per feature
Conventions to follow:
Add a new database backend feature
django/db/backends/base/base.pyStudy DatabaseWrapper base class for backend structure
Pattern: See how connection, cursor, and transaction methods are organized
django/db/backends/base/operations.pyAdd operation method to BaseDatabaseOperations
Pattern: See date_extract_sql(), datetime_cast_date_sql() for SQL generation patterns
django/db/backends/postgresql/operations.pyImplement backend-specific version in each backend
Pattern: See how PostgreSQL overrides base methods with pg-specific SQL
django/db/backends/base/features.pyAdd feature flag if needed
Pattern: See supports_json_field, can_introspect_json_field for feature detection
tests/backends/tests.pyAdd tests for your backend feature
Pattern: Follow BackendTestCase with skipUnlessDBFeature decorators
Conventions to follow:
Add a new form widget
django/forms/widgets.pyStudy existing widgets like TextInput, Select to understand Widget base class
Pattern: See how render(), get_context(), value_from_datadict() work together
django/forms/widgets.pyCreate your widget class inheriting from Widget or appropriate subclass
Pattern: Follow SelectDateWidget for complex multi-widget example
django/forms/templates/django/forms/widgets/Create template for your widget
Pattern: See input.html, select.html for widget template structure
tests/forms_tests/widget_tests/test_select.pyAdd tests for your widget
Pattern: Follow SelectTest structure with render and value extraction tests
Conventions to follow:
Coding Conventions
Standards and patterns used in this codebase
Use __all__ to explicitly define public API exports in module __init__.py files
__all__ = [
"ObjectDoesNotExist",
"EmptyResultSet",
"FieldDoesNotExist",
]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}")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.
"""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 = TrueUse RemovedInDjangoXXWarning classes with warnings.warn() for deprecation notices, following a two-version deprecation cycle
warnings.warn(FORMS_URLFIELD_ASSUME_HTTPS_DEPRECATED_MSG, RemovedInDjango60Warning)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")Use ESLint with specific globals configuration for Django admin JavaScript (django, jQuery, etc.)
globals: {
django: "readonly",
jQuery: "readonly",
grp: "readonly",
}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"Provide __main__.py for packages that should be executable via python -m
if __name__ == "__main__":
management.execute_from_command_line()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)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.pyGroup 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