or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

admin.mdauth.mdcontrib.mddatabase-orm.mdforms.mdhttp.mdindex.mdmigrations.mdmypy-plugin.mdsignals.mdtemplates.mdtransactions.mdurls.mdviews.md
tile.json

tessl/pypi-django-stubs

Comprehensive type stubs for Django framework enabling static type checking with mypy

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/django-stubs@4.2.x

To install, run

npx @tessl/cli install tessl/pypi-django-stubs@4.2.0

index.mddocs/

Django-Stubs

Django-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.

Package Information

  • Package Name: django-stubs
  • Language: Python
  • Installation: pip install django-stubs
  • Dependencies: django, django-stubs-ext>=4.2.7, typing-extensions, types-pytz, types-PyYAML
  • Optional: mypy~=1.7.0 (via django-stubs[compatible-mypy])

Core Imports

Django-stubs enables type checking by providing type stubs for Django modules:

import django
from django import setup

Common 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, ObjectDoesNotExist

Basic Usage

from 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'),
]

Architecture

Django-stubs provides two main components:

  • Type Stubs: 684 .pyi files mirroring Django's complete API structure with precise type annotations
  • MyPy Plugin: Enhanced type checking for Django-specific patterns, QuerySet operations, model field types, and request handling

This design enables full static type checking while preserving Django's dynamic capabilities and providing better IDE support through accurate type inference.

Capabilities

Database and ORM

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): ...

Database and ORM

Database Migrations

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): ...

Database Migrations

Database Transactions

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: ...

Database Transactions

Django Signals

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: ModelSignal

Django Signals

Forms System

Type 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): ...

Forms System

HTTP Handling

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): ...

HTTP Handling

URL Routing

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: ...

URL Routing

View System

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): ...

View System

Template System

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: ...

Template System

Administration Interface

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: AdminSite

Administration Interface

Authentication System

Type 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(): ...

Authentication System

Contrib Packages

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): ...

Contrib Packages

MyPy Plugin

Enhanced type checking plugin that provides Django-specific type inference for model fields, QuerySet operations, form processing, and request handling patterns.

class NewSemanalDjangoPlugin: ...

MyPy Plugin

Utilities and Shortcuts

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): ...

Configuration

settings: LazySettings

class Settings: ...
class LazySettings: ...

Exception Types

# 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): ...