Open-Source Wikis

/

Django

/

Systems

/

Contrib apps

django/django

Contrib apps

django/contrib/ is the home of optional, opt-in apps that ship with Django but aren't loaded unless added to INSTALLED_APPS. The contrib directory is older than the framework's "reusable apps" pattern — it's where Django incubates app-shaped functionality without making it mandatory.

What ships

django/contrib/
├── admin/          # the auto-generated admin interface (largest)
├── admindocs/      # admin documentation generator
├── auth/           # users, groups, permissions, password hashing
├── contenttypes/   # generic relations to any model
├── flatpages/      # CMS-lite (URL → HTML page)
├── gis/            # GeoDjango (geospatial fields, geometry types, GIS DB ops)
├── humanize/       # template filters: ordinal, naturalday, naturaltime
├── messages/       # one-shot user messages stored in session/cookie/DB
├── postgres/       # PostgreSQL-only fields, indexes, search, aggregates
├── redirects/      # database-driven redirect map
├── sessions/       # session middleware + backends
├── sitemaps/       # XML sitemap framework
├── sites/          # multi-site (Site model with domain/name)
├── staticfiles/    # collectstatic and dev-time static-file serving
└── syndication/    # RSS / Atom feed generation

Each app follows the same shape: an apps.py declaring an AppConfig, a models.py (where applicable), templates, migrations, and a tests.py skeleton (the real tests live in tests/<app>_tests/).

Big apps

admin (~70 source files)

The auto-generated admin interface. Builds a full CRUD site from ModelAdmin registrations. Major surface:

  • AdminSite (sites.py, ~23 KB) — the registry of admins, the URL builder, the entrypoints (AdminSite.get_urls()).
  • ModelAdmin (options.py, ~104 KB, the largest single file in django/) — per-model configuration: list_display, list_filter, search_fields, fieldsets, inlines, the change/add/delete views, custom actions.
  • InlineModelAdmin — for editing related rows inline on a parent's change view.
  • Filters (filters.py, ~28 KB) — list_filter implementation.
  • Helpers (helpers.py) — AdminForm, Fieldset, BoundField adapter classes used by the templates.
  • Checks (checks.py, ~52 KB) — system checks for admin configuration (one of the largest check modules).
  • Templatestemplates/admin/ is a full set of opinionated HTML/CSS.
  • Staticstatic/admin/ contains the admin's CSS, JS, and images.

The admin discovers admin.py modules in each installed app via admin.autodiscover(). The discovered registrations populate the default AdminSite instance (django.contrib.admin.site).

auth (~25 source files)

Authentication, authorisation, password management. Core types:

  • AbstractBaseUser (base_user.py) — minimal user model.
  • AbstractUser (models.py) — the standard user shape (username, email, names, dates, permissions).
  • User (models.py) — concrete AbstractUser subclass; the default AUTH_USER_MODEL.
  • Group, Permission (models.py) — group-based authorisation.
  • PermissionsMixin — adds is_superuser, groups, user_permissions.
  • Authentication backends (backends.py) — ModelBackend (default), AllowAllUsersModelBackend, RemoteUserBackend.
  • Hashers (hashers.py, ~24 KB) — PBKDF2PasswordHasher (default), Argon2PasswordHasher, BCryptSHA256PasswordHasher, ScryptPasswordHasher. Pluggable via PASSWORD_HASHERS.
  • Forms (forms.py, ~21 KB) — AuthenticationForm, UserCreationForm, PasswordResetForm, SetPasswordForm, PasswordChangeForm.
  • Views (views.py, ~14 KB) — login, logout, password reset (with email confirmation tokens), password change.
  • Middleware (middleware.py) — AuthenticationMiddleware (sets request.user lazily), LoginRequiredMiddleware, PersistentRemoteUserMiddleware.
  • Decorators / mixins@login_required, @permission_required, LoginRequiredMixin, PermissionRequiredMixin.
  • Password validators (password_validation.py) — MinimumLengthValidator, UserAttributeSimilarityValidator, CommonPasswordValidator (uses the gzipped wordlist), NumericPasswordValidator.

AUTH_USER_MODEL is settable to a custom model for projects that need richer user data. The framework guards swappable model handling throughout the ORM and admin.

gis (~120 source files)

GeoDjango. Adds geospatial fields, geometry types, and DB operations for PostGIS, SpatiaLite, MySQL, and Oracle Spatial. Major surface:

  • gdal/ — Python wrapper around GDAL (OGRGeometry, Layer, DataSource).
  • geos/ — Python wrapper around GEOS (Polygon, Point, LineString, …).
  • db/models/PointField, PolygonField, LineStringField, MultiPolygonField, plus geometry lookups.
  • db/backends/ — backend overrides for PostGIS, SpatiaLite (SQLite), MySQL, Oracle Spatial.
  • forms/ — geometry form fields and widgets (with map widgets).
  • admin/GISModelAdmin with map-aware change forms.
  • measure.pyDistance, Area value types.
  • geoip2.py — wrapper around the GeoIP2 database.

GIS is the most platform-dependent part of Django: it requires GEOS, GDAL, PROJ, and (for some backends) PostGIS or SpatiaLite to be installed at the system level.

postgres (~30 source files)

PostgreSQL-only goodies that don't make sense as cross-backend features:

  • FieldsArrayField, HStoreField, JSONField (legacy; prefer models.JSONField now), RangeField (IntegerRangeField, DecimalRangeField, DateRangeField, DateTimeRangeField).
  • AggregatesArrayAgg, BitAnd, BitOr, BoolAnd, BoolOr, JSONBAgg, StringAgg.
  • IndexesBrinIndex, BTreeIndex, GinIndex, GistIndex, HashIndex, SpGistIndex.
  • ConstraintsExclusionConstraint.
  • Search (search.py, ~16 KB) — full-text search wrappers (SearchVector, SearchQuery, SearchRank, TrigramSimilarity).
  • OperationsBtreeGinExtension, BtreeGistExtension, CITextExtension, CryptoExtension, HStoreExtension, TrigramExtension, UnaccentExtension — migration ops to enable PostgreSQL extensions.

django.contrib.postgres only loads cleanly when the database is PostgreSQL; the system checks gate it.

sessions

Server-side session storage with pluggable backends:

  • dbSession model in the database.
  • cache — store in the configured cache.
  • cached_db — cache + DB write-through.
  • file — disk files.
  • signed_cookies — store in a signed cookie (no server-side storage).

SessionMiddleware populates request.session lazily. The default backend is db.

staticfiles

Static file serving and the collectstatic command. Major pieces:

  • StorageStaticFilesStorage, ManifestStaticFilesStorage (hashed filenames for cache-busting).
  • FindersFileSystemFinder, AppDirectoriesFinder.
  • collectstatic management command — copy/hash all static files into STATIC_ROOT.
  • runserver override — adds --insecure flag and serves files from STATIC_URL in dev.
  • {% static %} template tag — generate URLs.

messages

One-shot user messages (e.g., "Saved!" after a form submit). Storage backends:

  • cookie — signed cookie (default).
  • session — server-side session.

@messages.success, @messages.error, @messages.warning, @messages.info, @messages.debug add messages from views. Templates iterate via {% for message in messages %}.

sites

A Site model with domain and name. Used by:

  • The contrib auth password reset email (to construct full URLs).
  • The flatpages, redirects, and syndication apps (to scope rows per site).
  • User code for multi-tenant deployments.

SITE_ID is the active site identifier. CurrentSiteMiddleware sets request.site.

Smaller apps

  • contenttypesContentType model and GenericForeignKey/GenericRelation for cross-model relations.
  • flatpages — simple URL-to-HTML pages stored in the DB.
  • humanize — template filters: ordinal, naturalday, naturaltime, intcomma.
  • redirects — DB-driven Redirect model + middleware that catches 404s.
  • syndication — RSS/Atom feed generation (the Feed class).
  • sitemaps — XML sitemap views from a Sitemap class.
  • admindocs — admin pages that document the project's models, views, tags, filters.

Patterns

AppConfig.ready() for signals

Most contrib apps use ready() to connect signals:

class ContentTypesConfig(AppConfig):
    name = "django.contrib.contenttypes"

    def ready(self):
        post_migrate.connect(create_contenttypes, sender=self)

This pattern is repeated in auth, sites, flatpages, etc.

Per-app system checks

Each contrib app with non-trivial configuration ships a checks.py:

  • auth/checks.py — verifies the user model.
  • admin/checks.py — verifies admin registrations.
  • contenttypes/checks.py — checks for stale contenttype rows.

Per-app templates and static

Each contrib app's templates live under templates/<app>/. Static assets (where applicable) live under static/<app>/. The default template loader (AppDirectoriesLoader) and static finder (AppDirectoriesFinder) discover them automatically.

Migrations

Every contrib app with models ships migrations under <app>/migrations/. They're kept in lockstep with model changes.

Integration points

  • Apps registry (apps and settings) — contrib apps are loaded just like user apps.
  • ORM (orm) — most contrib apps add models.
  • URL routing (urls) — many contrib apps ship URL patterns (urls.py) for include().
  • Templates (templates) — each contrib app ships a templates/ directory.
  • Migrations (migrations) — each contrib app with models ships migrations.

Entry points for modification

  • Bug in a contrib app: file a Trac ticket with the app label in the component field.
  • New contrib app: this is rare. Recent additions (Redis cache, content-security-policy middleware) have been merged into existing places rather than spun up as new contrib apps. The bar is high.
  • Replace a contrib app: define your own and add it to INSTALLED_APPS instead. The user model, session backend, mail backend, cache backend, and storage are all swappable.

Key source files (admin/auth selection)

File Purpose
django/contrib/admin/options.py ModelAdmin, change/add/delete views (~104 KB; the largest file in django/)
django/contrib/admin/sites.py AdminSite
django/contrib/admin/checks.py Admin system checks (~52 KB)
django/contrib/admin/filters.py list_filter framework
django/contrib/auth/models.py User, AbstractUser, Group, Permission
django/contrib/auth/hashers.py Password hashers (~24 KB)
django/contrib/auth/forms.py Auth forms
django/contrib/auth/views.py Login, logout, password reset views
django/contrib/auth/middleware.py AuthenticationMiddleware
django/contrib/auth/password_validation.py Password validators
django/contrib/sessions/backends/ Session storage backends
django/contrib/staticfiles/storage.py ManifestStaticFilesStorage
django/contrib/postgres/search.py Full-text search
django/contrib/contenttypes/fields.py GenericForeignKey, GenericRelation

Where to read tests

Each contrib app has a dedicated test app under tests/:

  • tests/admin_views/, tests/admin_filters/, tests/admin_inlines/, tests/admin_changelist/ (admin)
  • tests/auth_tests/
  • tests/contenttypes_tests/
  • tests/flatpages_tests/
  • tests/gis_tests/
  • tests/messages_tests/
  • tests/postgres_tests/
  • tests/redirects_tests/
  • tests/sessions_tests/
  • tests/sites_tests/
  • tests/staticfiles_tests/
  • tests/sitemaps_tests/
  • tests/syndication_tests/

Built by Factory AutoWiki from public repository content. It is a generated preview for codebase exploration, not source-maintained documentation.

Contrib apps – Django wiki | Factory