Skip to main content

django-types PyPI

Type stubs for Django.

Note: this project was forked from https://github.com/typeddjango/django-stubs with the goal of removing the mypy plugin dependency so that mypy can't crash due to Django config, and that non-mypy type checkers like pyright will work better with Django.

install

pip install django-types

If you're on a Django version < 3.1, you'll need to monkey patch Django's QuerySet and Manager classes so we can index into them with a generic argument. You can either use django-stubs-ext or do this yourself manually:

# in settings.py
from django.db.models.manager import BaseManager
from django.db.models.query import QuerySet

# NOTE: there are probably other items you'll need to monkey patch depending on
# your version.
for cls in (QuerySet, BaseManager):
    cls.__class_getitem__ = classmethod(lambda cls, *args, **kwargs: cls)  # type: ignore [attr-defined]

usage

getting objects to work

By default the base Model class doesn't have objects defined, so you'll have to explicitly type the property.

from django.db import connection, models
from django.db.models.manager import Manager

class User(models.Model):
    title = models.CharField(max_length=255)

    objects = Manager["User"]()

reveal_type(User.objects.all().first())
# note: Revealed type is 'Optional[User]'

ForeignKey ids as properties in ORM models

When defining a Django ORM model with a foreign key, like so:

class User(models.Model):
    team = models.ForeignKey("Team", null=True, on_delete=models.SET_NULL)

two properties are created, team as expected, and team_id. In order for mypy to know about the id property we need to define it manually as follows:

from typing import TYPE_CHECKING

class User(models.Model):
    team = models.ForeignKey("Team", null=True, on_delete=models.SET_NULL)
    if TYPE_CHECKING:
        team_id: int

AutoField

By default Django will create an AutoField for you if one doesn't exist.

For type checkers to know about the id field you'll need to declare the field explicitly.

# before
class Post(models.Model):
    ...

# after
class Post(models.Model):
    id = models.AutoField(primary_key=True)

HttpRequest's user property

The HttpRequest's user property has a type of Union[AbstractBaseUser, AnonymousUser], but for most of your views you'll probably want either an authed user or an AnonymousUser.

So we can define a subclass for each case:

class AuthedHttpRequest(HttpRequest):
    user: User  # type: ignore [assignment]

And then you can use it in your views:

@auth.login_required
def activity(request: AuthedHttpRequest, team_id: str) -> HttpResponse:
    ...

You can also get more strict with your login_required decorator so that the first argument of the fuction it is decorating is AuthedHttpRequest:

from typing import Any, Union, TypeVar, cast
from django.http import HttpRequest, HttpResponse
from typing_extensions import Protocol
from functools import wraps

class RequestHandler1(Protocol):
    def __call__(self, request: AuthedHttpRequest) -> HttpResponse:
        ...


class RequestHandler2(Protocol):
    def __call__(self, request: AuthedHttpRequest, __arg1: Any) -> HttpResponse:
        ...


RequestHandler = Union[RequestHandler1, RequestHandler2]


# Verbose bound arg due to limitations of Python typing.
# see: https://github.com/python/mypy/issues/5876
_F = TypeVar("_F", bound=RequestHandler)


def login_required(view_func: _F) -> _F:
    @wraps(view_func)
    def wrapped_view(
        request: AuthedHttpRequest, *args: object, **kwargs: object
    ) -> HttpResponse:
        if request.user.is_authenticated:
            return view_func(request, *args, **kwargs)  # type: ignore [call-arg]
        raise AuthenticationRequired

    return cast(_F, wrapped_view)

Then the following will type error:

@auth.login_required
def activity(request: HttpRequest, team_id: str) -> HttpResponse:
    ...

Metadata

Release files for django-types-extra 0.6.5

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for django-types-extra 0.6.5
File Size Uploaded Provenance Actions
django-types-extra-0.6.5.tar.gz 186.7 kB Without provenance Details for django-types-extra-0.6.5.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for django-types-extra 0.6.5
File Interpreter ABI Platform Actions
django_types_extra-0.6.5-py3-none-any.whl Python 3 none any Details for django_types_extra-0.6.5-py3-none-any.whl

Total release size: 566.0 kB

Release files / django-types-extra-0.6.5.tar.gz

Download URL django-types-extra-0.6.5.tar.gz
Size 186.7 kB
Tags Source
SHA-256 checksum
How to use checksums
13917c590b4d12cc770c4f27f87a9315e7d81c6a04f19b802b0ffbe36f2e196f
BLAKE2b-256 checksum
How to use checksums
1733e555f94c667259b6731158f9fbf5eae81ea25cd7b22ae5cf114d2d250705
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.1.7 CPython/3.9.6 Darwin/20.4.0

Release files / django_types_extra-0.6.5-py3-none-any.whl

Download URL django_types_extra-0.6.5-py3-none-any.whl
Size 379.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
5288e3a2ab7cc51cc80182abac30c8f0d24973ac71a39e47623791a4d48c7f44
BLAKE2b-256 checksum
How to use checksums
91bba47bdcb0ef9dde068cee141bd1e5d7a195b0bd1166785843ae129354b267
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.1.7 CPython/3.9.6 Darwin/20.4.0

Security for django-types-extra 0.6.5

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page