Comprehensive type stubs for Django framework enabling static type checking with mypy
—
Django's contributed applications provide extended functionality including geographic information systems (GIS), PostgreSQL-specific features, static file handling, sessions, messaging, and multi-site support.
Comprehensive GIS support for geographic and spatial data processing.
# GIS Model Fields
class GeometryField(models.Field):
"""
Base geometry field for spatial data.
Stores geometric objects with spatial database support.
"""
def __init__(self, verbose_name: str = None, srid: int = 4326, spatial_index: bool = True,
dim: int = 2, geography: bool = False, extent: tuple = None, tolerance: float = 0.05, **kwargs): ...
class PointField(GeometryField):
"""
Field for storing point geometries (longitude, latitude).
Represents single geographic points with coordinate data.
"""
class LineStringField(GeometryField):
"""
Field for storing line string geometries.
Represents connected series of points forming lines or paths.
"""
class PolygonField(GeometryField):
"""
Field for storing polygon geometries.
Represents closed geometric shapes with area boundaries.
"""
class MultiPointField(GeometryField):
"""
Field for storing collections of points.
Represents multiple discrete geographic points.
"""
class MultiLineStringField(GeometryField):
"""
Field for storing collections of line strings.
Represents multiple line segments or polylines.
"""
class MultiPolygonField(GeometryField):
"""
Field for storing collections of polygons.
Represents complex areas with multiple polygon boundaries.
"""
class GeometryCollectionField(GeometryField):
"""
Field for storing mixed geometry collections.
Represents heterogeneous collections of various geometry types.
"""
# GIS Database Functions
class Distance(models.Expression):
"""
Database function for calculating distance between geometries.
"""
def __init__(self, expr1, expr2, spheroid: bool = None, **extra): ...
class Area(models.Expression):
"""
Database function for calculating geometry area.
"""
class Centroid(models.Expression):
"""
Database function for finding geometry centroid.
"""
class Length(models.Expression):
"""
Database function for calculating geometry length.
"""
class Perimeter(models.Expression):
"""
Database function for calculating polygon perimeter.
"""
class Transform(models.Expression):
"""
Database function for transforming geometry coordinates.
"""
def __init__(self, expression, srid: int, **extra): ...
# GIS Lookup Types
class DWithin(models.Lookup):
"""
Lookup for geometries within specified distance.
"""
class Intersects(models.Lookup):
"""
Lookup for geometries that intersect.
"""
class Contains(models.Lookup):
"""
Lookup for geometries that contain another geometry.
"""
class Overlaps(models.Lookup):
"""
Lookup for geometries that overlap.
"""
class Touches(models.Lookup):
"""
Lookup for geometries that touch boundaries.
"""
class Within(models.Lookup):
"""
Lookup for geometries within another geometry.
"""
class Crosses(models.Lookup):
"""
Lookup for geometries that cross.
"""Enhanced functionality for PostgreSQL database features.
# PostgreSQL Fields
class ArrayField(models.Field):
"""
Field for storing PostgreSQL arrays.
Stores ordered collections of values with indexing support.
"""
def __init__(self, base_field: models.Field, size: int = None, default: list = list, **kwargs): ...
class HStoreField(models.Field):
"""
Field for storing PostgreSQL hstore key-value data.
Stores flexible key-value pairs with indexing and querying.
"""
def __init__(self, **kwargs): ...
class JSONField(models.Field):
"""
Field for storing JSON data in PostgreSQL.
Stores structured JSON data with native database support.
"""
def __init__(self, encoder=None, decoder=None, **kwargs): ...
class CICharField(models.CharField):
"""
Case-insensitive character field for PostgreSQL.
Uses citext extension for case-insensitive text storage.
"""
class CIEmailField(models.EmailField):
"""
Case-insensitive email field for PostgreSQL.
"""
class CITextField(models.TextField):
"""
Case-insensitive text field for PostgreSQL.
"""
# Range Fields
class IntegerRangeField(models.Field):
"""
Field for storing integer ranges.
Stores continuous or discrete integer ranges with bounds.
"""
class BigIntegerRangeField(models.Field):
"""
Field for storing big integer ranges.
"""
class DecimalRangeField(models.Field):
"""
Field for storing decimal number ranges.
"""
class DateTimeRangeField(models.Field):
"""
Field for storing datetime ranges.
"""
class DateRangeField(models.Field):
"""
Field for storing date ranges.
"""
# Full-text Search Fields
class SearchVectorField(models.Field):
"""
Field for storing PostgreSQL full-text search vectors.
Optimizes text search with pre-computed search vectors.
"""
class SearchQueryField(models.Field):
"""
Field for storing search queries.
"""
class SearchRankField(models.Field):
"""
Field for storing search result rankings.
"""
# PostgreSQL Aggregates
class ArrayAgg(models.Aggregate):
"""
Aggregate function for creating arrays from grouped values.
"""
def __init__(self, expression, distinct: bool = False, filter=None, default=None, ordering=(), **extra): ...
class BoolAnd(models.Aggregate):
"""
Aggregate function for boolean AND operations.
"""
class BoolOr(models.Aggregate):
"""
Aggregate function for boolean OR operations.
"""
class JSONBAgg(models.Aggregate):
"""
Aggregate function for creating JSONB arrays.
"""
class StringAgg(models.Aggregate):
"""
Aggregate function for concatenating strings.
"""
def __init__(self, expression, delimiter: str, distinct: bool = False, filter=None, default=None, ordering=(), **extra): ...
# PostgreSQL Indexes
class BrinIndex(models.Index):
"""
Block Range Index for large tables.
"""
def __init__(self, *, fields: list, name: str, autosummarize: bool = None, pages_per_range: int = None, **kwargs): ...
class BTreeIndex(models.Index):
"""
B-tree index (default PostgreSQL index).
"""
class GinIndex(models.Index):
"""
Generalized Inverted Index for composite values.
"""
def __init__(self, *, fields: list, name: str, fastupdate: bool = None, gin_pending_list_limit: int = None, **kwargs): ...
class GistIndex(models.Index):
"""
Generalized Search Tree index for spatial data.
"""
def __init__(self, *, fields: list, name: str, buffering: bool = None, fillfactor: int = None, **kwargs): ...
class HashIndex(models.Index):
"""
Hash index for equality comparisons.
"""
class SpGistIndex(models.Index):
"""
Space-partitioned Generalized Search Tree index.
"""
def __init__(self, *, fields: list, name: str, fillfactor: int = None, **kwargs): ...
# PostgreSQL Constraints
class ExclusionConstraint(models.BaseConstraint):
"""
Exclusion constraint for PostgreSQL.
Ensures no two rows satisfy specified condition simultaneously.
"""
def __init__(self, *, name: str, expressions: list, index_type: str = None, condition=None,
deferrable: bool = None, include: list = None, opclasses: list = None): ...
# PostgreSQL Operations
class HStoreExtension(migrations.Operation):
"""
Migration operation for enabling hstore extension.
"""
class CITextExtension(migrations.Operation):
"""
Migration operation for enabling citext extension.
"""
class TrigramExtension(migrations.Operation):
"""
Migration operation for enabling pg_trgm extension.
"""
class UnaccentExtension(migrations.Operation):
"""
Migration operation for enabling unaccent extension.
"""Session management with multiple storage backends.
class SessionBase:
"""
Base session interface for all session backends.
Provides common session functionality across different storage methods.
"""
TEST_COOKIE_NAME: str = 'testcookie'
TEST_COOKIE_VALUE: str = 'worked'
def __init__(self, session_key: str = None): ...
def __contains__(self, key: str) -> bool: ...
def __getitem__(self, key: str): ...
def __setitem__(self, key: str, value) -> None: ...
def __delitem__(self, key: str) -> None: ...
def keys(self): ...
def items(self): ...
def values(self): ...
def get(self, key: str, default=None): ...
def pop(self, key: str, default=None): ...
def setdefault(self, key: str, value): ...
def set_test_cookie(self) -> None: ...
def test_cookie_worked(self) -> bool: ...
def delete_test_cookie(self) -> None: ...
def flush(self) -> None: ...
def delete(self, session_key: str = None) -> None: ...
def cycle_key(self) -> None: ...
def is_empty(self) -> bool: ...
def get_session_cookie_age(self) -> int: ...
def get_expiry_age(self, **kwargs) -> int: ...
def get_expiry_date(self, **kwargs): ...
def set_expiry(self, value) -> None: ...
def get_expire_at_browser_close(self) -> bool: ...
def clear_expired(cls) -> None: ...
def save(self, must_create: bool = False) -> None: ...
def exists(self, session_key: str) -> bool: ...
def create(self) -> None: ...
def load(self) -> dict: ...
session_key: str
accessed: bool
modified: bool
class SessionStore(SessionBase):
"""
Database-backed session storage.
Stores session data in database Session model.
"""
class CachedSessionStore(SessionStore):
"""
Session storage using cache with database fallback.
Combines cache performance with database persistence.
"""
cache_key_prefix: str = 'django.contrib.sessions.cached_db'
class CacheSessionStore(SessionBase):
"""
Cache-only session storage.
Stores session data entirely in cache system.
"""
cache_key_prefix: str = 'django.contrib.sessions.cache'
class FileSessionStore(SessionBase):
"""
File-based session storage.
Stores session data in individual files on filesystem.
"""
def __init__(self, session_key: str = None): ...
def file_path(self, session_key: str = None) -> str: ...
class CookieSessionStore(SessionBase):
"""
Client-side session storage using signed cookies.
Stores session data in browser cookies with cryptographic signing.
"""
# Session Model
class Session(models.Model):
"""
Database model for session storage.
Stores session data with expiration and key management.
"""
session_key: models.CharField
session_data: models.TextField
expire_date: models.DateTimeField
objects: SessionManager
@classmethod
def get_session_store_class(cls): ...
def get_decoded(self) -> dict: ...
def get_session_store(import_path: str = None) -> SessionBase:
"""
Get session store instance by import path.
Args:
import_path: Dotted path to session store class
Returns:
Session store instance
"""Static file collection, serving, and management utilities.
# Static Files Finders
class BaseFinder:
"""
Base class for static file finders.
Abstract interface for locating static files from various sources.
"""
def find(self, path: str, all: bool = False) -> str: ...
def list(self, ignore_patterns: list) -> list: ...
class FileSystemFinder(BaseFinder):
"""
Finder for static files in STATICFILES_DIRS.
Locates files from configured static directories.
"""
class AppDirectoriesFinder(BaseFinder):
"""
Finder for static files in app directories.
Locates files from 'static' folders in installed apps.
"""
class DefaultStorageFinder(BaseFinder):
"""
Finder using default file storage backend.
Locates files from configured default storage.
"""
# Static Files Storage
class StaticFilesStorage(FileSystemStorage):
"""
File storage for collected static files.
Standard storage backend for static file collection.
"""
class ManifestStaticFilesStorage(StaticFilesStorage):
"""
Static files storage with manifest-based versioning.
Adds file hashing and manifest generation for cache busting.
"""
manifest_version: str = '1.0'
manifest_name: str = 'staticfiles.json'
manifest_strict: bool = True
def __init__(self, location: str = None, base_url: str = None, file_permissions_mode: int = None,
directory_permissions_mode: int = None, manifest_storage=None): ...
def hashed_name(self, name: str, content=None, filename: str = None) -> str: ...
def url(self, name: str, force: bool = False) -> str: ...
def load_manifest(self) -> dict: ...
def save_manifest(self) -> None: ...
class CachedStaticFilesStorage(ManifestStaticFilesStorage):
"""
Deprecated alias for ManifestStaticFilesStorage.
"""
# Static Files Management
def collect_static_files(verbosity: int = 1, interactive: bool = True, dry_run: bool = False,
clear: bool = False, link: bool = False, use_default_ignore_patterns: bool = True,
ignore_patterns: list = None) -> dict:
"""
Collect static files from all configured sources.
Args:
verbosity: Output verbosity level
interactive: Whether to prompt for user input
dry_run: Show actions without executing
clear: Clear existing files before collecting
link: Create symbolic links instead of copying
use_default_ignore_patterns: Use default ignore patterns
ignore_patterns: Additional patterns to ignore
Returns:
Dictionary of collection statistics
"""
def get_finders() -> list:
"""
Get list of configured static file finders.
Returns:
List of finder instances
"""
def find_static_file(path: str, all: bool = False) -> str:
"""
Find static file using configured finders.
Args:
path: Static file path to find
all: Return all matches instead of first
Returns:
File path or list of paths if all=True
"""
# Static Files Template Tags
def static(path: str) -> str:
"""
Template tag for generating static file URLs.
Args:
path: Static file path
Returns:
Full URL to static file
"""
def get_static_prefix() -> str:
"""
Template tag for getting static files URL prefix.
Returns:
STATIC_URL setting value
"""
def get_media_prefix() -> str:
"""
Template tag for getting media files URL prefix.
Returns:
MEDIA_URL setting value
"""Multi-site support for sharing Django projects across domains.
class Site(models.Model):
"""
Model representing a website/domain in multi-site setup.
Associates content and configuration with specific domains.
"""
domain: models.CharField
name: models.CharField
objects: SiteManager
def __str__(self) -> str: ...
def natural_key(self) -> tuple: ...
def get_absolute_url(self) -> str: ...
class SiteManager(models.Manager):
"""
Manager for Site model with caching support.
"""
use_in_migrations: bool = True
def get_current(self, request: HttpRequest = None) -> Site: ...
def clear_cache(self) -> None: ...
def get_by_natural_key(self, domain: str) -> Site: ...
def get_current_site(request: HttpRequest) -> Site:
"""
Get current site from request.
Args:
request: HTTP request object
Returns:
Current Site instance
"""User messaging system for displaying notifications and alerts.
# Message Levels
DEBUG: int = 10
INFO: int = 20
SUCCESS: int = 25
WARNING: int = 30
ERROR: int = 40
DEFAULT_LEVELS: dict = {
DEBUG: 'debug',
INFO: 'info',
SUCCESS: 'success',
WARNING: 'warning',
ERROR: 'error',
}
# Message Classes
class Message:
"""
Individual message with level and content.
Represents a single notification or alert for users.
"""
def __init__(self, level: int, message: str, extra_tags: str = ''): ...
def _prepare(self) -> None: ...
def __str__(self) -> str: ...
def __eq__(self, other) -> bool: ...
level: int
message: str
extra_tags: str
level_tag: str
class MessageFailure(Exception):
"""
Exception raised when message cannot be added.
"""
# Message Storage Backends
class BaseStorage:
"""
Base message storage backend.
Abstract interface for storing user messages across requests.
"""
request: HttpRequest
def __init__(self, request: HttpRequest): ...
def __len__(self) -> int: ...
def __iter__(self): ...
def __contains__(self, item: Message) -> bool: ...
def add(self, level: int, message: str, extra_tags: str = '') -> None: ...
def _get_level(self) -> int: ...
def _set_level(self, value: int) -> None: ...
def _store(self, messages: list, response: HttpResponse, *args, **kwargs) -> None: ...
def _get(self, *args, **kwargs) -> tuple: ...
def update(self, response: HttpResponse) -> None: ...
level: int
class SessionStorage(BaseStorage):
"""
Session-based message storage.
Stores messages in user session data.
"""
session_key: str = '_messages'
class CookieStorage(BaseStorage):
"""
Cookie-based message storage.
Stores messages in signed browser cookies.
"""
cookie_name: str = 'messages'
max_cookie_size: int = 2048
class FallbackStorage(BaseStorage):
"""
Combined session and cookie storage with fallback.
Uses session storage with cookie fallback for reliability.
"""
storage_classes: tuple = (CookieStorage, SessionStorage)
# Message Functions
def add_message(request: HttpRequest, level: int, message: str, extra_tags: str = '', fail_silently: bool = False) -> None:
"""
Add message to request.
Args:
request: HTTP request object
level: Message level (DEBUG, INFO, SUCCESS, WARNING, ERROR)
message: Message content
extra_tags: Additional CSS classes
fail_silently: Don't raise exception on failure
"""
def get_messages(request: HttpRequest) -> list:
"""
Get messages from request storage.
Args:
request: HTTP request object
Returns:
List of Message objects
"""
def debug(request: HttpRequest, message: str, extra_tags: str = '', fail_silently: bool = False) -> None:
"""Add debug message."""
def info(request: HttpRequest, message: str, extra_tags: str = '', fail_silently: bool = False) -> None:
"""Add info message."""
def success(request: HttpRequest, message: str, extra_tags: str = '', fail_silently: bool = False) -> None:
"""Add success message."""
def warning(request: HttpRequest, message: str, extra_tags: str = '', fail_silently: bool = False) -> None:
"""Add warning message."""
def error(request: HttpRequest, message: str, extra_tags: str = '', fail_silently: bool = False) -> None:
"""Add error message."""
def get_level(request: HttpRequest) -> int:
"""
Get minimum message level for request.
Args:
request: HTTP request object
Returns:
Current message level
"""
def set_level(request: HttpRequest, level: int) -> None:
"""
Set minimum message level for request.
Args:
request: HTTP request object
level: New message level
"""
# Message Middleware
class MessageMiddleware:
"""
Middleware for processing user messages.
Handles message storage and retrieval across requests.
"""
def __init__(self, get_response): ...
def __call__(self, request: HttpRequest) -> HttpResponse: ...
def process_response(self, request: HttpRequest, response: HttpResponse) -> HttpResponse: ...Generic relations and content type introspection.
class ContentType(models.Model):
"""
Model representing installed Django model types.
Provides generic foreign key support and model introspection.
"""
app_label: models.CharField
model: models.CharField
objects: ContentTypeManager
def __str__(self) -> str: ...
def name(self) -> str: ...
def model_class(self): ...
def get_object_for_this_type(self, **kwargs): ...
def get_all_objects_for_this_type(self, **kwargs): ...
def natural_key(self) -> tuple: ...
class ContentTypeManager(models.Manager):
"""
Manager for ContentType with caching and lookup methods.
"""
use_in_migrations: bool = True
def get_for_model(self, model, for_concrete_model: bool = True) -> ContentType: ...
def get_for_models(self, *models, for_concrete_models: bool = True) -> dict: ...
def get_by_natural_key(self, app_label: str, model: str) -> ContentType: ...
def clear_cache(self) -> None: ...
# Generic Foreign Keys
class GenericForeignKey:
"""
Generic foreign key to any model type.
Provides flexible relationships using content types.
"""
def __init__(self, ct_field: str = 'content_type', fk_field: str = 'object_id', for_concrete_model: bool = True): ...
def get_content_type(self, obj=None, id=None, using: str = None) -> ContentType: ...
def get_cached_value(self, instance, default=None): ...
def set_cached_value(self, instance, value) -> None: ...
def is_cached(self, instance) -> bool: ...
class GenericRelation(models.ForeignKey):
"""
Reverse generic foreign key relationship.
Provides reverse access to generic foreign key relationships.
"""
def __init__(self, to: str, object_id_field: str = 'object_id', content_type_field: str = 'content_type',
for_concrete_model: bool = True, related_query_name: str = None, limit_choices_to: dict = None, **kwargs): ...
# Generic Inline Admin
class GenericInlineModelAdmin:
"""
Admin interface for generic foreign key relationships.
"""
ct_field: str = 'content_type'
ct_fk_field: str = 'object_id'
formset = None
def get_formset(self, request: HttpRequest, obj=None, **kwargs): ...
class GenericStackedInline(GenericInlineModelAdmin):
"""
Stacked layout for generic inline admin.
"""
template: str = 'admin/edit_inline/stacked.html'
class GenericTabularInline(GenericInlineModelAdmin):
"""
Tabular layout for generic inline admin.
"""
template: str = 'admin/edit_inline/tabular.html'Template filters for human-friendly data formatting.
def apnumber(value: int) -> str:
"""
Convert numbers 1-9 to Associated Press style.
Args:
value: Number to convert
Returns:
AP style number or original if > 9
"""
def intcomma(value: int) -> str:
"""
Add commas to integer for thousands separation.
Args:
value: Number to format
Returns:
Number with comma separators
"""
def intword(value: int) -> str:
"""
Convert large integers to human-readable format.
Args:
value: Number to convert
Returns:
Human-readable number (e.g., "1.2 million")
"""
def naturalday(value, arg: str = None) -> str:
"""
Convert date to natural language relative to today.
Args:
value: Date to convert
arg: Date format for non-today dates
Returns:
Natural language date ("today", "yesterday", "tomorrow")
"""
def naturaltime(value) -> str:
"""
Convert datetime to natural language relative to now.
Args:
value: Datetime to convert
Returns:
Natural language time ("2 hours ago", "in 3 minutes")
"""
def ordinal(value: int) -> str:
"""
Convert integer to ordinal form.
Args:
value: Number to convert
Returns:
Ordinal number string ("1st", "2nd", "3rd", "4th")
"""Install with Tessl CLI
npx tessl i tessl/pypi-django-stubs