Package: django-stubs-adb
pep484 stubs for DjangoThis 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 versionpython version1.14.00.990+3.2.x or 4.0.x or 4.1.x^3.71.13.00.980+3.2.x or 4.0.x or 4.1.x^3.71.12.00.931+3.2.x or 4.0.x^3.71.11.00.931+3.2.x^3.71.10.00.931+3.2.x^3.71.9.00.9103.2.x^3.61.8.00.8123.1.x^3.61.7.00.7902.2.x || 3.x^3.61.6.00.7802.2.x || 3.x^3.61.5.00.7702.2.x || 3.x^3.61.4.00.7602.2.x || 3.x^3.61.3.00.7502.2.x || 3.x^3.61.2.00.7302.2.x^3.61.1.00.7202.2.x^3.60.12.xold semantic analyzer (<0.711), dmypy support2.1.x^3.6FAQIs 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()Note: This monkey patching approach will only work when using Python 3.7 and higher, when the__class_getitem__magic method was introduced.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.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!