Package: django-stubs
This package containstype stubsand a custom mypy plugin to provide more precise static types and type inference for Django framework. Django uses some Python "magic" that makes having precise types for some code patterns problematic. This is why we need this project. The final goal is to be able to get precise types for most common patterns.Installationpipinstalldjango-stubs[compatible-mypy]To make mypy aware of the plugin, you need to add[mypy]plugins=mypy_django_plugin.main[mypy.plugins.django-stubs]django_settings_module="myproject.settings"in yourmypy.iniorsetup.cfgfile.pyproject.tomlconfigurations are also supported:[tool.mypy]plugins=["mypy_django_plugin.main"][tool.django-stubs]django_settings_module="myproject.settings"Two things happening here:We need to explicitly list our plugin to be loaded bymypyOur plugin also requiresdjangosettings module (what you put intoDJANGO_SETTINGS_MODULEvariable) to be specifiedThis fully workingtyped boilerplatecan serve you as an example.Version compatibilityWe rely on differentdjangoandmypyversions:django-stubsMypy versionDjango versionDjango partial supportPython version4.2.71.7.x4.24.1, 3.23.8 - 3.124.2.61.6.x4.24.1, 3.23.8 - 3.124.2.51.6.x4.24.1, 3.23.8 - 3.124.2.41.5.x4.24.1, 3.23.8 - 3.114.2.31.4.x4.24.1, 3.23.8 - 3.114.2.21.4.x4.24.1, 3.23.8 - 3.114.2.11.3.x4.24.1, 3.23.8 - 3.114.2.01.2.x4.24.1, 4.0, 3.23.7 - 3.111.16.01.1.x4.14.0, 3.23.7 - 3.111.15.01.0.x4.14.0, 3.23.7 - 3.111.14.00.990+4.14.0, 3.23.7 - 3.11FeaturesType checking of Model Meta attributesBy inheriting from theTypedModelMetaclass, you can ensure you're using correct types for
attributes:fromdjango.dbimportmodelsfromdjango_stubs_ext.db.modelsimportTypedModelMetaclassMyModel(models.Model):example=models.CharField(max_length=100)classMeta(TypedModelMeta):ordering=["example"]constraints=[models.UniqueConstraint(fields=["example"],name="unique_example"),]Other typed base classesdjango_stubs_ext.db.router.TypedDatabaseRoutercan be used as base when implementing custom database routers.Settingsdjango-stubs has a few settings, which you can list in:pyproject.toml, under the table[tool.django-stubs]mypy.iniunder the table[mypy.plugins.django-stubs]The supported settings are:django_settings_module, a string.Specify the import path of your settings module, the same as Django’sDJANGO_SETTINGS_MODULEenvironment variable.strict_settings, a boolean, defaulttrue.Set tofalseif using dynamic settings, asdescribed below.FAQIs this an official Django project?No, it is not. We are independent from Django at the moment.
There's aproposalto merge our project into the Django itself.
You can show your support by liking the PR.Is it safe to use this in production?Yes, it is! This project does not affect your runtime at all.
It only affectsmypytype checking process.But, it does not make any sense to use this project withoutmypy.mypy crashes when I run it with this plugin installedThe current implementation uses Django's runtime to extract information about models, so it might crash if your installed apps ormodels.pyare broken.In other words, if yourmanage.py runservercrashes, mypy will crash too.
You can also runmypywith--tboption to get extra information about the error.I cannot use QuerySet or Manager with type annotationsYou can get aTypeError: 'type' object is not subscriptablewhen you will try to useQuerySet[MyModel],Manager[MyModel]or some other Django-based Generic types.This happens because these Django classes do not support__class_getitem__magic method in runtime.You can go with ourdjango_stubs_exthelper, that patches all the types we use as Generic in django.Install it:pipinstalldjango-stubs-ext# as a production dependencyAnd then place in your top-level settings:importdjango_stubs_extdjango_stubs_ext.monkeypatch()You can add extra types to patch withdjango_stubs_ext.monkeypatch(extra_classes=[YourDesiredType])You can use strings instead:'QuerySet[MyModel]'and'Manager[MyModel]', this way it will work as a type formypyand as a regularstrin runtime.How can I create a HttpRequest that's guaranteed to have an authenticated user?Django's built inHttpRequesthas the attributeuserthat resolves to the typeUnion[User,AnonymousUser]whereUseris the user model specified by theAUTH_USER_MODELsetting.If you want aHttpRequestthat you can type-annotate with where you know that the user is authenticated you can subclass the normalHttpRequestclass like so:fromdjango.httpimportHttpRequestfrommy_user_app.modelsimportMyUserclassAuthenticatedHttpRequest(HttpRequest):user:MyUserAnd then useAuthenticatedHttpRequestinstead of the standardHttpRequestfor when you know that the user is authenticated. For example in views using the@login_requireddecorator.My QuerySet methods are returning Any rather than my ModelIf you are usingMyQuerySet.as_manager():Example:fromdjango.dbimportmodelsclassMyModelQuerySet(models.QuerySet):passclassMyModel(models.Model):bar=models.IntegerField()objects=MyModelQuerySet.as_manager()defuse_my_model()->int:foo=MyModel.objects.get(id=1)# Should now be `MyModel`returnfoo.xyz# Gives an errorOr if you're usingManager.from_queryset:Example:fromdjango.dbimportmodelsclassMyModelQuerySet(models.QuerySet):passMyModelManager=models.Manager.from_queryset(MyModelQuerySet)classMyModel(models.Model):bar=models.IntegerField()objects=MyModelManager()defuse_my_model()->int:foo=MyModel.objects.get(id=1)# Should now be `MyModel`returnfoo.xyz# Gives an errorWhy am I getting incompatible return type errors on my custom managers?If you declare your custom managers without generics and override built-in
methods you might see an error message about incompatible error messages,
something like this:fromdjango.dbimportmodelsclassMyManager(model.Manager):defcreate(self,**kwargs)->"MyModel":passwill cause this error message:error: Return type "MyModel" of "create" incompatible with return type "_T" in supertype "BaseManager"This is happening because theManagerclass is generic, but without
specifying generics the built-in manager methods are expected to return the
generic type of the base manager, which is any model. To fix this issue you
should declare your manager with your model as the type variable:classMyManager(models.Manager["MyModel"]):...How do I annotate cases where I called QuerySet.annotate?Django-stubs provides a special type,django_stubs_ext.WithAnnotations[Model], which indicates that theModelhas
been annotated, meaning it allows getting/setting extra attributes on the model instance.Optionally, you can provide aTypedDictof these attributes,
e.g.WithAnnotations[MyModel, MyTypedDict], to specify which annotated attributes are present.Currently, the mypy plugin can recognize that specific names were passed toQuerySet.annotateand
include them in the type, but does not record the types of these attributes.The knowledge of the specific annotated fields is not yet used in creating more specific types forQuerySet'svalues,values_list, orfiltermethods, however knowledge that the model was annotatedisused to create a
broader type result type forvalues/values_list, and to allowfiltering on any field.fromtypingimportTypedDictfromdjango_stubs_extimportWithAnnotationsfromdjango.dbimportmodelsfromdjango.db.models.expressionsimportValueclassMyModel(models.Model):username=models.CharField(max_length=100)deffunc(m:WithAnnotations[MyModel])->str:returnm.asdf# OK, since the model is annotated as allowing any attributefunc(MyModel.objects.annotate(foo=Value("")).get(id=1))# OKfunc(MyModel.objects.get(id=1))# Error, since this model will not allow access to any attributeclassMyTypedDict(TypedDict):foo:strdeffunc2(m:WithAnnotations[MyModel,MyTypedDict])->str:print(m.bar)# Error, since field "bar" is not in MyModel or MyTypedDict.returnm.foo# OK, since we said field "foo" was allowedfunc(MyModel.objects.annotate(foo=Value("")).get(id=1))# OKfunc(MyModel.objects.annotate(bar=Value("")).get(id=1))# ErrorHow do I check if something is an instance of QuerySet in runtime?A limitation of makingQuerySetgeneric is that you can not use
it forisinstancechecks.fromdjango.db.models.queryimportQuerySetdeffoo(obj:object)->None:ifisinstance(obj,QuerySet):# Error: Parameterized generics cannot be used with class or instance checks...To get around with this issue without makingQuerySetnon-generic,
Django-stubs providesdjango_stubs_ext.QuerySetAny, a non-generic
variant ofQuerySetsuitable for runtime type checking:fromdjango_stubs_extimportQuerySetAnydeffoo(obj:object)->None:ifisinstance(obj,QuerySetAny):# OK...Why am I getting incompatible argument type mentioning_StrPromise?The lazy translation functions of Django (such asgettext_lazy) return aPromiseinstead ofstr. These two typescannot be used interchangeably. The return type of these functions was thereforechangedto reflect that.If you encounter this error in your own code, you can either cast thePromisetostr(causing the translation to be evaluated), or use theStrPromiseorStrOrPromisetypes fromdjango-stubs-extin type hints. Which solution to choose depends depends on the particular case. Seeworking with lazy translation objectsin the Django documentation for more information.If this is reported on Django code, please report an issue or open a pull request to fix the type hints.How to use a custom library to handle Django settings?Using something likedjango-split-settingsordjango-configurationswill make it hard for mypy to infer your settings.This might also be the case when using something like:try:from.local_settingsimport*exceptException:passSo, mypy would not like this code:fromdjango.confimportsettingssettings.CUSTOM_VALUE# E: 'Settings' object has no attribute 'CUSTOM_SETTING'To handle this corner case we have a special settingstrict_settings(Trueby default),
you can switch it toFalseto always returnAnyand not raise any errors if runtime settings module has the given value,
for examplepyproject.toml:[tool.django-stubs]strict_settings=falseormypy.ini:[mypy.plugins.django-stubs]strict_settings=falseAnd then:# Works:reveal_type(settings.EXISTS_IN_RUNTIME)# N: Any# Errors:reveal_type(settings.MISSING)# E: 'Settings' object has no attribute 'MISSING'Related projectsawesome-python-typing- Awesome list of all typing-related things in Python.djangorestframework-stubs- Stubs for Django REST Framework.pytest-mypy-plugins-pytestplugin that we use for testingmypystubs and plugins.wemake-django-template- Create new typed Django projects in seconds.To get helpWe have Gitter here:https://gitter.im/mypy-django/LobbyIf you think you have more generic typing issue, please refer tohttps://github.com/python/mypyand their Gitter.ContributingThis project is open source and community driven. As such we encourage contributions big and small. You can contribute by doing any of the following:Contribute code (e.g. improve stubs, add plugin capabilities, write tests etc) - to do so please follow thecontribution guide.Assist in code reviews and discussions in issues.Identify bugs and issues and report theseAsk and answer questions onStackOverflowYou can always also reach out in gitter to discuss your contributions!