Comprehensive type stubs for Django framework enabling static type checking with mypy
npx @tessl/cli install tessl/pypi-django-stubs@4.2.0Django-stubs provides comprehensive type stubs for the Django web framework, enabling precise static type checking with mypy. It addresses Django's dynamic nature and provides type definitions for Django's models, views, forms, admin interface, authentication system, and all major framework components, along with a mypy plugin for enhanced type inference.
pip install django-stubsdjango, django-stubs-ext>=4.2.7, typing-extensions, types-pytz, types-PyYAMLmypy~=1.7.0 (via django-stubs[compatible-mypy])Django-stubs enables type checking by providing type stubs for Django modules:
import django
from django import setupCommon Django imports with type support:
# Database and models
from django.db import models
from django.db.models import QuerySet, Manager
from django.db import transaction
# HTTP request/response handling
from django.http import HttpRequest, HttpResponse, JsonResponse
from django.shortcuts import render, get_object_or_404, redirect
# URL routing
from django.urls import path, include, reverse
# Forms
from django import forms
from django.forms import ModelForm
# Views
from django.views import View
from django.views.generic import ListView, DetailView, CreateView, UpdateView
# Admin
from django.contrib import admin
# Authentication
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
# Configuration
from django.conf import settings
from django.core.exceptions import ValidationError, ObjectDoesNotExistfrom django.db import models
from django.http import HttpRequest, HttpResponse
from django.shortcuts import render
# Define a model with proper type hints
class Article(models.Model):
title: models.CharField = models.CharField(max_length=200)
content: models.TextField = models.TextField()
created_at: models.DateTimeField = models.DateTimeField(auto_now_add=True)
# View function with type hints
def article_detail(request: HttpRequest, article_id: int) -> HttpResponse:
article = get_object_or_404(Article, pk=article_id)
return render(request, 'article_detail.html', {'article': article})
# URL configuration
from django.urls import path
from . import views
urlpatterns = [
path('article/<int:article_id>/', views.article_detail, name='article_detail'),
]Django-stubs provides two main components:
.pyi files mirroring Django's complete API structure with precise type annotationsThis design enables full static type checking while preserving Django's dynamic capabilities and providing better IDE support through accurate type inference.
Complete type definitions for Django's Object-Relational Mapping system, including model classes, field types, QuerySet operations, database connections, and relationship definitions.
class Model: ...
class QuerySet: ...
class Manager: ...
# Field types
class CharField(Field): ...
class IntegerField(Field): ...
class ForeignKey(Field): ...
class ManyToManyField(Field): ...
# Query functions
def get_object_or_404(klass, *args, **kwargs): ...Type definitions for Django's migrations system, providing version control for database schema changes with automated creation, modification, and rollback of database structures.
class Migration: ...
class CreateModel(Operation): ...
class AddField(Operation): ...
class AlterField(Operation): ...
class RunSQL(Operation): ...
class RunPython(Operation): ...Type definitions for Django's transaction system, providing database transaction management with atomic operations, savepoints, and commit/rollback functionality.
class Atomic: ...
def atomic(using=None, savepoint=True, durable=False) -> Atomic: ...
def commit(using=None) -> None: ...
def rollback(using=None) -> None: ...
def savepoint(using=None) -> str: ...
def on_commit(func, using=None, robust=True) -> None: ...Type definitions for Django's signal system, providing decoupled notifications for actions happening throughout the framework with event-driven programming patterns.
class Signal: ...
class ModelSignal(Signal): ...
def receiver(signal, sender=None, weak=True, dispatch_uid=None) -> Callable: ...
# Model signals
pre_save: ModelSignal
post_save: ModelSignal
pre_delete: ModelSignal
post_delete: ModelSignalType definitions for Django's form handling system, including form classes, field types, widgets, validation, and form processing utilities.
class Form: ...
class ModelForm(Form): ...
class Field: ...
# Form fields
class CharField(Field): ...
class EmailField(Field): ...
class ChoiceField(Field): ...
# Widgets
class TextInput(Widget): ...
class Select(Widget): ...Type definitions for HTTP request and response processing, including request objects, response classes, middleware, and cookie handling.
class HttpRequest: ...
class HttpResponse: ...
class JsonResponse(HttpResponse): ...
class QueryDict: ...
# HTTP exceptions
class Http404(Exception): ...Type definitions for Django's URL routing system, including URL patterns, view resolution, reverse URL lookup, and URL configuration.
def path(route: str, view, kwargs=None, name=None) -> URLPattern: ...
def include(arg, namespace=None) -> tuple: ...
def reverse(viewname: str, urlconf=None, args=None, kwargs=None, current_app=None) -> str: ...
class URLPattern: ...
class URLResolver: ...Type definitions for Django's view system, including class-based views, generic views, template views, and view mixins.
class View: ...
class TemplateView(View): ...
class ListView(View): ...
class DetailView(View): ...
class CreateView(View): ...
class UpdateView(View): ...Type definitions for Django's template engine system, including template loading, context processing, template tags, and filters.
class Template: ...
class Context: ...
class Engine: ...
def render(request, template_name: str, context=None, content_type=None, status=None, using=None) -> HttpResponse: ...Type definitions for Django's admin interface, including admin site configuration, model admin classes, inline admin, and admin actions.
class ModelAdmin: ...
class StackedInline: ...
class TabularInline: ...
def register(model_or_iterable, admin_class=None, **options): ...
site: AdminSiteType definitions for Django's authentication and authorization system, including user models, authentication backends, permissions, and session handling.
def authenticate(request=None, **credentials): ...
def login(request: HttpRequest, user) -> None: ...
def logout(request: HttpRequest) -> None: ...
def get_user_model(): ...Type definitions for Django's contributed applications including GIS (GeoDjango), PostgreSQL-specific features, static files handling, sessions, messaging, and more.
# GIS fields
class PointField(Field): ...
class PolygonField(Field): ...
# PostgreSQL fields
class ArrayField(Field): ...
class JSONField(Field): ...Enhanced type checking plugin that provides Django-specific type inference for model fields, QuerySet operations, form processing, and request handling patterns.
class NewSemanalDjangoPlugin: ...def render(request, template_name: str, context=None, content_type=None, status=None, using=None) -> HttpResponse: ...
def redirect(to, *args, permanent=False, **kwargs) -> HttpResponse: ...
def get_object_or_404(klass, *args, **kwargs): ...
def get_list_or_404(klass, *args, **kwargs): ...settings: LazySettings
class Settings: ...
class LazySettings: ...# Database exceptions
class DatabaseError(Exception): ...
class IntegrityError(DatabaseError): ...
# HTTP exceptions
class Http404(Exception): ...
# URL exceptions
class NoReverseMatch(Exception): ...
# Template exceptions
class TemplateDoesNotExist(Exception): ...
# Form exceptions
class ValidationError(Exception): ...