Skip to content

Instantly share code, notes, and snippets.

@thibaudcolas
Last active December 11, 2025 09:19
Show Gist options
  • Select an option

  • Save thibaudcolas/6073ab19995fa71f67e60f7f88307cfe to your computer and use it in GitHub Desktop.

Select an option

Save thibaudcolas/6073ab19995fa71f67e60f7f88307cfe to your computer and use it in GitHub Desktop.
PR templates AI disclosure requirements

Testing proposed AI policy inclusion in PR template for django/django: Extended the GitHub pull request template to require AI assistance disclosure. #19594.

Copies of all generated agent guidelines, with relevant excerpts in this README.

OpenAI Codex

  • PRs target main and fill .github/pull_request_template.md: include ticket number (or N/A), branch description, AI assistance disclosure, and checklist items.

Warp

The .github/pull_request_template.md file wasn’t detected.

Claude Code

AI-Assisted Contributions

When using AI tools (including Claude Code):

  • You must disclose AI tool usage in the PR template
  • You must fully review and verify all AI-generated output
  • Ensure code aligns with Django's architecture and passes the full test suite
  • Unverified AI contributions may be closed without review

Mistral Vibe

Agent Contributions

When submitting code that was generated or significantly modified by an agent:

  1. Clearly indicate which parts were agent-assisted
  2. Provide information about the agent used
  3. Ensure the code follows Django's coding standards
  4. Be prepared to explain and defend the agent's suggestions
  5. Take responsibility for the quality of the submission

Generated with OpenAI Codex (gpt-5.1-codex-max)


Repository Guidelines

Project Structure & Module Organization

  • django/: main framework packages; app directories mirror Django’s built-in contrib/apps layout.
  • tests/: Python test suite mirrors django/ paths (e.g., tests/forms_tests/ for django/forms/); runtests.py drives execution.
  • docs/: Sphinx sources; see docs/README for building HTML and make targets.
  • js_tests/: JavaScript/admin tests run with npm; keep fixtures in sync with Python tests.
  • scripts/, extras/, demo_env/: helper scripts, sample configs, and a demo setup for local experimenting.

Build, Test, and Development Commands

  • Install deps: python -m pip install -r tests/requirements/py3.txt (plus database-specific requirements files if needed); editable install with python -m pip install -e ..
  • Full suite: python -m tox -e py3 (creates env, runs all Python tests from tests/).
  • Targeted Python tests: ./runtests.py shortcuts or ./runtests.py forms_tests.tests.test_forms.FormsTestCase.test_cleaned_data.
  • Linters/formatters: python -m tox -e black -e isort -e flake8; docs spelling: python -m tox -e docs.
  • JavaScript: python -m tox -e javascript (runs npm install then npm test from repo root).

Coding Style & Naming Conventions

  • Python: 4-space indentation, PEP 8, prefer explicit imports; keep lines readable and avoid overlong expressions.
  • Formatting and import order are enforced by black (check-only) and isort; lint with flake8.
  • Tests follow test_*.py and Test* naming; co-locate regression tests near the affected module.
  • Docs use reStructuredText with Sphinx roles; keep :ref: and .. versionadded:: markers consistent.

Testing Guidelines

  • Use Django’s test runner via ./runtests.py; pass a label to scope by app or test path for faster feedback.
  • Add regression coverage with minimal fixtures; prefer SimpleTestCase/TestCase over heavier integration when possible.
  • For optional databases, install matching tests/requirements/*.txt and run with --settings or dedicated tox envs (e.g., -e postgres).
  • JavaScript changes should be covered in js_tests/ and aligned with related Python behaviors when applicable.

Commit & Pull Request Guidelines

  • Commits mirror existing history: short past-tense statements with Trac ticket references and a period, e.g., Fixed #12345 -- Clarified middleware docs..
  • PRs target main and fill .github/pull_request_template.md: include ticket number (or N/A), branch description, AI assistance disclosure, and checklist items.
  • Link or update the Trac ticket (“Has patch”), include tests/docs updates, and attach light/dark screenshots for UI tweaks.
  • Keep diffs focused; prefer smaller, reviewable changes and note any follow-ups or compatibility considerations in the PR description.

Agents in Django

This document provides an overview of agents and their role in the Django project.

What are Agents?

Agents are automated systems or tools that assist in various aspects of the Django project. They can help with:

  • Code generation and refactoring
  • Documentation updates
  • Test case creation
  • Bug triaging and issue management
  • Code review and quality assurance
  • Translation and localization
  • Dependency management
  • Release automation

Types of Agents

1. AI-Assisted Development Agents

These agents use artificial intelligence to assist developers in writing, reviewing, and maintaining code. They can:

  • Suggest code improvements
  • Generate boilerplate code
  • Identify potential bugs
  • Provide documentation assistance
  • Help with code refactoring

2. Continuous Integration Agents

These agents run automated tests and checks to ensure code quality:

  • Run test suites
  • Check code style and formatting
  • Verify documentation
  • Perform security scans
  • Check for regressions

3. Documentation Agents

These agents help maintain and improve Django's documentation:

  • Generate API documentation
  • Update release notes
  • Maintain changelogs
  • Improve documentation structure
  • Ensure documentation consistency

4. Translation Agents

These agents assist with Django's internationalization efforts:

  • Manage translation files
  • Coordinate with translators
  • Update language catalogs
  • Ensure translation consistency

Agent Guidelines

When using agents in the Django project:

  1. Transparency: Always disclose when agents are used to generate or modify code
  2. Quality: Ensure agent-generated code meets Django's quality standards
  3. Review: All agent-generated code should be reviewed by human maintainers
  4. Attribution: Properly attribute agent contributions when required
  5. Ethics: Use agents responsibly and ethically

Agent Contributions

When submitting code that was generated or significantly modified by an agent:

  1. Clearly indicate which parts were agent-assisted
  2. Provide information about the agent used
  3. Ensure the code follows Django's coding standards
  4. Be prepared to explain and defend the agent's suggestions
  5. Take responsibility for the quality of the submission

Agent Tools

Django may use various agent tools including:

  • Code generation tools
  • AI-assisted coding platforms
  • Automated testing frameworks
  • Documentation generators
  • Translation management systems

Reporting Agent Issues

If you encounter issues with agent-generated code or agent behavior:

  1. Report the issue to the Django maintainers
  2. Provide details about the agent used
  3. Include specific examples of problematic code
  4. Suggest improvements or alternatives

Future of Agents in Django

As agent technology evolves, Django will continue to explore ways to:

  • Improve code quality through agent assistance
  • Automate repetitive tasks
  • Enhance developer productivity
  • Maintain high standards while leveraging agent capabilities
  • Ensure ethical and responsible use of agent technology

For more information about contributing to Django, including agent-assisted contributions, please see our Contributing Documentation.%

Generated with Claude Code (Sonnet 4.5)


CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

Overview

Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. This repository contains the Django core codebase, including the ORM, template system, admin interface, and various contrib applications.

Development Commands

Running Tests

# Install dependencies (from repo root)
cd tests
python -m pip install -e ..
python -m pip install -r requirements/py3.txt

# Run all tests
./runtests.py

# Run specific test module
./runtests.py <module_name>
# Example: ./runtests.py generic_relations i18n

# Run specific test class
./runtests.py <module_name>.tests.<TestClass>
# Example: ./runtests.py i18n.tests.TranslationTests

# Run specific test method
./runtests.py <module_name>.tests.<TestClass>.<test_method>
# Example: ./runtests.py i18n.tests.TranslationTests.test_lazy_objects

# Run tests with debug SQL logging
./runtests.py <module_name> --debug-sql --verbosity=2

# Run tests in serial (to see full tracebacks)
./runtests.py <module_name> --parallel=1

# Run selenium tests
./runtests.py --selenium=firefox,chrome --headless

# Test bisection (to find interfering tests)
./runtests.py --bisect <failing_test>

# Test pairing (to find tests with side-effects)
./runtests.py --pair <failing_test>

Code Quality Checks

# Install and run pre-commit hooks
python -m pip install pre-commit
pre-commit install
pre-commit run --all-files

# Run all checks with tox
python -m pip install tox
tox

# Run specific linters
tox -e black      # Code formatting
tox -e isort      # Import sorting
tox -e flake8     # Linting
tox -e docs       # Documentation spelling check

# Format code manually
black .
isort django tests scripts

# Run JavaScript tests
tox -e javascript
# or: npm install && npm test

Documentation

cd docs
make html           # Build HTML documentation
make spelling       # Run spelling checker

Code Architecture

Main Django Package Structure

  • django/apps/ - Application registry and configuration
  • django/conf/ - Configuration and settings system
  • django/contrib/ - Optional "contrib" applications (admin, auth, contenttypes, sessions, messages, staticfiles, gis, postgres, etc.)
  • django/core/ - Core functionality including management commands, mail, cache backends, signing, signals, validators, and the WSGI/ASGI interface
  • django/db/ - Database layer including the ORM, query system, migrations, and database backends
  • django/dispatch/ - Signal dispatching system
  • django/forms/ - Form handling and rendering
  • django/http/ - HTTP request/response handling
  • django/middleware/ - Middleware components
  • django/template/ - Template system
  • django/test/ - Testing framework
  • django/urls/ - URL routing and resolving
  • django/utils/ - Utility functions and helpers
  • django/views/ - View classes and functions

Test Structure

Tests are located in the tests/ directory with each app or feature having its own subdirectory:

  • Tests for django.contrib.auth are in tests/auth_tests/
  • Tests for django.contrib.admin are in tests/admin_*/ directories
  • Each test directory typically contains models.py, tests.py, and potentially urls.py

Database Backend System

Django supports multiple database backends through a common interface:

  • Backend implementations are in django/db/backends/
  • Each backend (postgresql, mysql, sqlite3, oracle) implements standard operations
  • DatabaseFeatures class defines capabilities and limitations per backend
  • DatabaseOperations class provides database-specific SQL operations
  • Tests can be skipped based on backend features using @skipUnlessDBFeature decorator

ORM Architecture

  • Models (django/db/models/): Core ORM functionality
    • Model base class provides database table representation
    • Manager provides query interface
    • QuerySet represents a database query (lazy evaluation)
    • Field types defined in fields/
    • Lookups and transforms for query filtering
  • Queries (django/db/models/sql/): SQL generation layer
    • Query class builds SQL queries
    • SQLCompiler converts queries to backend-specific SQL
  • Migrations (django/db/migrations/): Schema evolution
    • Migration class represents a migration file
    • Operations (AddField, RemoveField, etc.) define schema changes
    • autodetector.py generates migrations from model changes

Template System

  • Engines (django/template/backends/): Support for different template engines (Django, Jinja2)
  • Loaders (django/template/loaders/): Load templates from various sources
  • Context processors add variables to template context
  • Template tags and filters extend template functionality

Admin Interface

  • django/contrib/admin/ contains the automatic admin interface
  • ModelAdmin classes configure model representation in admin
  • Admin views handle CRUD operations
  • Inlines allow editing related models
  • Filters, search, and ordering configured per model

Coding Standards

Python Style

  • Formatting: Use Black with 88 character line limit (enforced by pre-commit)
  • Import sorting: Use isort with Black profile
  • Linting: Follow PEP 8 with exceptions noted in .flake8
  • String formatting: Use f-strings for simple cases, .format() or % for translations
  • Naming: snake_case for variables/functions, InitialCaps for classes
  • Avoid "we" in comments: Write "Loop over items" not "We loop over items"

Import Organization

Imports should be grouped in this order:

  1. Future imports
  2. Standard library
  3. Third-party libraries
  4. Other Django components (absolute imports)
  5. Local Django component (relative imports)
  6. Try/except imports

Within each group, sort alphabetically. Use isort to automate this.

Testing Practices

  • All bug fixes must include regression tests
  • All new features must include tests
  • Use @isolate_apps() decorator when defining models in tests to avoid polluting the app registry
  • Use assertRaisesMessage() and assertWarnsMessage() instead of assertRaises()/assertWarns()
  • Use assertIs(…, True/False) for boolean testing
  • Test docstrings should state expected behavior without preambles like "Tests that"
  • Run tests with --bisect to find interfering tests
  • Run tests with --pair to find tests with side-effects

AI-Assisted Contributions

When using AI tools (including Claude Code):

  • You must disclose AI tool usage in the PR template
  • You must fully review and verify all AI-generated output
  • Ensure code aligns with Django's architecture and passes the full test suite
  • Unverified AI contributions may be closed without review

Contribution Workflow

Before Starting

  1. Create a Trac ticket at https://code.djangoproject.com/ (required for non-trivial changes)
  2. Claim the ticket to let others know you're working on it
  3. Fork the repository on GitHub

Making Changes

  1. Work on the main branch (backports are handled by mergers)
  2. Write code that follows the coding standards
  3. Add or update tests for your changes
  4. Add or update documentation if needed
  5. Ensure commit messages are in past tense, mention ticket number, and end with a period
    • Example: "Fixed #12345 -- Added support for composite primary keys."

Submitting Changes

  1. Run the test suite to ensure all tests pass
  2. Run code quality checks (black, isort, flake8)
  3. Create a pull request on GitHub
  4. Fill out the PR template including:
    • Trac ticket number (format: ticket-XXXXX)
    • Branch description
    • AI assistance disclosure (required)
    • Checklist items
  5. Check the "Has patch" box on the Trac ticket

Important Notes

  • PRs without Trac tickets will be closed (except trivial typos)
  • The project uses Trac for issue tracking, not GitHub Issues
  • Sign the Contributor License Agreement (CLA) for non-trivial contributions
  • Target the main branch for all PRs
  • Include screenshots in both light and dark modes for UI changes

Database Requirements for Testing

The test suite requires two databases configured in settings:

  • default: Primary test database
  • other: Secondary database (same backend as default, different name)

Test databases are created with test_ prefix and automatically deleted after tests.

For PostgreSQL/MySQL/Oracle testing:

  • User must have CREATE DATABASE permission
  • Configure DATABASES setting in a custom test settings file
  • Use --settings=your_settings with runtests.py

Common Patterns

Database Feature Checks

from django.db import connection

if connection.features.supports_json_field:
    # Use JSON field functionality

Signal Usage

from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=MyModel)
def my_handler(sender, instance, created, **kwargs):
    # Handle signal

Custom Lookups

from django.db.models import Lookup

class NotEqual(Lookup):
    lookup_name = 'ne'

    def as_sql(self, compiler, connection):
        lhs, lhs_params = self.process_lhs(compiler, connection)
        rhs, rhs_params = self.process_rhs(compiler, connection)
        params = lhs_params + rhs_params
        return '%s <> %s' % (lhs, rhs), params

Model Inheritance

Django supports three types of model inheritance:

  1. Abstract base classes: Meta.abstract = True - fields added to child models
  2. Multi-table inheritance: Creates separate tables with automatic joins
  3. Proxy models: Meta.proxy = True - same table, different Python behavior

macOS Development

On macOS High Sierra and newer, set environment variable to avoid test hangs:

export OBJC_DISABLE_INITIALIZE_FORK_SAFETY=YES

Add to ~/.profile or ~/.bashrc to make permanent.

Generated with Warp (auto mode)


WARP.md

This file provides guidance to WARP (warp.dev) when working with code in this repository.

Core Architecture

Django is organized into several major subsystems:

  • django/core/ - Core framework functionality including handlers, management commands, and mail
  • django/db/ - ORM, database backends, and migrations
  • django/contrib/ - "Batteries included" apps (admin, auth, contenttypes, sessions, etc.)
  • django/http/ - Request/response handling
  • django/template/ - Template engine
  • django/forms/ - Form handling
  • django/views/ - View layer including generic views
  • django/urls/ - URL routing
  • django/middleware/ - Request/response middleware
  • django/utils/ - Utility functions
  • django/conf/ - Settings and configuration

Request/Response Lifecycle

The request lifecycle flows through:

  1. WSGI/ASGI handler receives request
  2. Middleware chain processes request (defined in settings.MIDDLEWARE)
  3. URL resolver matches URL pattern and routes to view
  4. View processes request and returns response
  5. Middleware chain processes response
  6. Response sent to client

Key files: django/core/handlers/base.py, django/urls/resolvers.py

ORM Architecture

The ORM is centered around:

  • Model: Base class in django/db/models/base.py
  • QuerySet: Lazy query evaluation in django/db/models/query.py
  • Manager: Model.objects interface in django/db/models/manager.py
  • Backends: Database-specific implementations in django/db/backends/

Commands

Running Tests

Django uses a custom test runner located in tests/runtests.py.

Run all tests:

cd tests
./runtests.py

Run specific test module:

cd tests
./runtests.py i18n

Run specific test class:

cd tests
./runtests.py i18n.tests.TranslationTests

Run specific test method:

cd tests
./runtests.py i18n.tests.TranslationTests.test_lazy_objects

Run tests with settings:

cd tests
./runtests.py --settings=test_sqlite generic_relations

Run tests in parallel:

cd tests
./runtests.py --parallel auto

Testing with tox

Run all checks (tests, linting, formatting):

tox

Run specific environment:

tox -e py3          # Run tests
tox -e black        # Check black formatting
tox -e flake8       # Run flake8 linter
tox -e isort        # Check import sorting
tox -e docs         # Check documentation spelling
tox -e javascript   # Run JavaScript tests

Code Quality

Check code formatting (black):

black --check --diff .

Apply black formatting:

black .

Check import sorting (isort):

isort --check-only --diff django tests scripts

Apply import sorting:

isort django tests scripts

Run flake8:

flake8 .

Pre-commit Hooks

Install pre-commit hooks:

python -m pip install pre-commit
pre-commit install

Run pre-commit on all files:

pre-commit run --all-files

Documentation

Build documentation:

cd docs
make html

Check documentation spelling:

cd docs
make spelling

Code Style

Python

  • Use black for formatting (88 character line length)
  • Use isort for import sorting
  • Follow PEP 8 with Django-specific conventions
  • Use snake_case for variables/functions/methods, InitialCaps for classes
  • Docstrings follow PEP 257
  • Max line length: 88 characters for code, 79 for docstrings/comments

Import Order

  1. Future imports
  2. Standard library
  3. Third-party libraries
  4. Django components (absolute imports)
  5. Local Django components (relative imports)
  6. try/except imports

Alphabetize within each group.

String Formatting

Use %-formatting, f-strings, or str.format() for readability. F-strings should only use plain variable/property access. Never use f-strings for translatable strings.

Testing

  • Use assertRaisesMessage() and assertWarnsMessage() instead of plain assertRaises() and assertWarns()
  • Use assertIs(…, True/False) for testing boolean values
  • Test docstrings should state expected behavior without preambles like "Tests that"

Contributing Guidelines

Workflow

Django requires a Trac ticket for non-trivial changes:

  1. File a ticket at https://code.djangoproject.com/newticket
  2. Create a pull request on GitHub referencing the ticket
  3. PRs without tickets will be closed

Test Requirements

Before submitting changes:

  1. Run relevant tests: cd tests && ./runtests.py <module>
  2. Verify formatting: black --check .
  3. Verify imports: isort --check-only django tests scripts
  4. Run linter: flake8 .
  5. Or use tox to run all checks: tox

All tests must pass - Django maintains a policy of all tests passing at all times.

Test Dependencies

Core dependencies (required):

  • asgiref >= 3.9.1
  • sqlparse >= 0.5.0

Install test dependencies:

cd tests
python -m pip install -r requirements/py3.txt

For specific database backends:

python -m pip install -r requirements/postgres.txt
python -m pip install -r requirements/mysql.txt
python -m pip install -r requirements/oracle.txt

Python Version Support

Django requires Python 3.12+. The codebase uses modern Python features including:

  • Type hints (where applicable)
  • Async/await for async views and handlers
  • Dataclasses and other Python 3.12+ features
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment