PEP-484 stubs for django-rest-framework

Overview

mypy logo

pep484 stubs for Django REST framework

Build Status Checked with mypy Gitter

Mypy stubs for DRF 3.12.x. Supports Python 3.6, 3.7, 3.8 and 3.9.

Installation

pip install djangorestframework-stubs

To make mypy aware of the plugin, you need to add

[mypy]
plugins =
    mypy_drf_plugin.main

in your mypy.ini file.

To get help

We have Gitter here: https://gitter.im/mypy-django/Lobby If you think you have more generic typing issue, please refer to https://github.com/python/mypy and their Gitter.

Contributing

This project is open source and community driven. As such we encourage contributions big and small. You can contribute by doing any of the following:

  1. Contribute code (e.g. improve stubs, add plugin capabilities, write tests etc) - to do so please follow the contribution guide.
  2. Assist in code reviews and discussions in issues.
  3. Identify bugs and issues and report these

You can always also reach out in gitter to discuss your contributions!

Comments
  • Update to mypy 0.950

    Update to mypy 0.950

    I have made things!

    Requires django-stubs to be released with mypy 0.950 support (https://github.com/typeddjango/django-stubs/pull/939)

    I think it also depends on #213, mypy 0.950 doesn't like django-stubs 1.10.1.

    Related issues

    • Depends on: #213
    • Depends on: https://github.com/typeddjango/django-stubs/pull/939
    opened by intgr 8
  • Make serializers less strict

    Make serializers less strict

    Hi @Goldziher, in your https://github.com/typeddjango/djangorestframework-stubs/pull/94/files you made a lot of improvements to the serializer's types, so I decided to try it in one of my projects and provide some feedback.

    First of all thanks for your work it looks like you spent a lot of time working on that pr, the main problem that I see right now is that types become too specific, for example serializer generic signature https://github.com/typeddjango/djangorestframework-stubs/blob/master/rest_framework-stubs/serializers.pyi#L94 class BaseSerializer(Generic[_VT, _DT, _RP, _IN], Field[_VT, _DT, _RP, _IN]): with such signature I have to provide 4 types or not provide types at all so all generics become Any. Here why I think _VT, _DT and _RP are not that useful

    • _VT - used in initial and default attributes, you can easily provide that in code when needed
    class S(Serializer):
         initial: InitialType
         default: DefaultType
    
         def __init__(..., initial: IntitialType, defautl: DefaultType,...):
    
    • _DT - data that seriailzer will validate, it should be typed as Any or maybe Union[dict, list], because main use case is that you accept anything as data and want to validate that it valid input

    • _RP - representation method result, not sure why we should care about that type, it mostly internally used inside def data so it's better to have data return specific type instead of Any, anyway no reason to make it generic, you can easily override method return signature if you need it.

    Basically when I work with serializer I care about these things:

    • instance type
    • result of the serialization serializer.data
    • result of the validation serializer.validated_data

    Of all of that cases I would argue that only instance type worth to make generic, because it used in signatures of a lot of methods, while you can always override result signature for data or validated_data methods when needed. So I would change signature to Seriailizer(Generict[_IN]) until mypy has support for default values for generic eg. Serailizer(Generic[_IN, _DT = Any, ...]).

    Another problem is that these methods + def validate works with OrderedDict, first of all that should be a dict because the ordering of the dict is not important for these methods, second is that user can write serializer(many=True) and these methods now must work with List[dict] instead of dict. So I would change their signature back to:

        def update(self, instance: Model, validated_data: Any) -> Any: ...
        def create(self, validated_data: Any) -> Any: ...
        def save(self, **kwargs: Any) -> Any: ...
        def validate(self, attrs: Any) -> Any: ...
    

    I'm happy to discuss these and provide more feedback as soon as we get these things resolved, right now after drf-stubs update I get 220 type errors and problems described above make a big portion of it.

    opened by kalekseev 8
  • Sync, update and debug against DRF

    Sync, update and debug against DRF

    This PR is a major overhaul of the typings in this package. What it does:

    1. It syncs and adds almost all missing data from the latest version of the DRF
    2. It fixes a lot of the previous typings and updates these to be in sync with the DRF
    3. It adds significant improvements to typings - especially using generics for fields, relations and serialisers
    4. It adds testing against the DRF test suit
    5. It fully debugs the typings of this package and all changes against this test suit (this took me more than 30 hours to do).

    What remains to be done:

    1. finish fix travis
    opened by Goldziher 8
  • Specify `client` attribute of TestCase classes as APIClient

    Specify `client` attribute of TestCase classes as APIClient

    • Fixes the following issue when you use self.client in any DRF test class Incompatible types in assignment (expression has type "HttpResponse", variable has type "Response")

    Description

    I've recently upgraded to the latest master of both repos and ran into the above error. The issue seems to be that DRF APITestCase classes seem to be revealing type as HttpResponse instead of drf Response. The correctclient_class type hints exist here. But this alone doesn't seem enough to correctly type check all uses of the client. If one uses self.client inside a test method the client class still gets Client class instead of APIClient, because of the django-stubs here.

    This new error could be because of the recent changes to django-stubs that have surfaced additional type hints?

    Sample Test case

    
    from rest_framework.test import APITestCase
    from rest_framework.response import Response
    
    class MyTest(APITestCase):
        ...
        
        def test_method(self):
           # error:
           # Incompatible types in assignment (expression has type "HttpResponse", variable has type "Response")
           response: Response = self.client.post("/dummy")
    
    
    opened by sidmitra 7
  • Add APIClient type to test cases

    Add APIClient type to test cases

    client_class is explicitly set to APIClient in rest_framework/test.py, but I suppose that the client is created dynamically, thus drf-stubs have no idea that it should be an APIClient and not a Client warning me about response.data and client.force_authenticate.

    opened by MarcinWieczorek 7
  • Version 1.8.0 release

    Version 1.8.0 release

    @sobolevn Let's make a release, there's a significant number of things in master, including full compatibility with django-stubs 1.13.0, Python 3.10 and mypy 0.991.

    I have created draft release notes at https://github.com/typeddjango/djangorestframework-stubs/releases

    This PR also tweaks a few places in documentation:

    • Updated Python compatibility in setup.py and README.
    • Removed DRF version from README -- it has been out of date for a while.
    • Added link to typeshed coding conventions that's now enforced by flake8-pyi
    opened by intgr 6
  • Introduce `flake8-pyi` in `pre-commit` checks

    Introduce `flake8-pyi` in `pre-commit` checks

    I have made things!

    This is a PR similar to https://github.com/typeddjango/django-stubs/pull/1253, only for rest_framework-stubs.

    All statements that are unclear on how to proceed are marked with # noqa: in the code, with the exception of compat.pyi, which has additional rules turned off in setup.cfg.

    There are some low-hanging fruits to fix, e.g. https://github.com/typeddjango/djangorestframework-stubs/blob/89f8925c67027a759ca08c3643934aa8de107859/rest_framework-stubs/fields.pyi#L350 should obviously be

    max_whole_digits: int | None
    

    or https://github.com/typeddjango/djangorestframework-stubs/blob/89f8925c67027a759ca08c3643934aa8de107859/rest_framework-stubs/routers.pyi#L60 which could be set to default_schema_renderers: None, or removed altogether.

    opened by hoefling 6
  • Fixes #230 - Add missing attributes to APIClient method Response objects

    Fixes #230 - Add missing attributes to APIClient method Response objects

    I have made things!

    Related issues

    Closes #230

    I'm not absolutely certain the test is in the right place but it does appear to exercise the changed code. Thank you in advance for any feedback!

    opened by mattwwarren 6
  • Fix status.HTTP_200_OK

    Fix status.HTTP_200_OK

    status.HTTP_200_OK should be Literal[200], not Literal[202]. Fixes #123.

    I cannot run pytest because of #124, but I don't see how this could break anything.

    opened by vhtkrk 6
  • Typings for Field attributes

    Typings for Field attributes

    Currently a lot of Field's attributes are not exposed in types, eg:

    error: "ChoiceField" has no attribute "field_name"
    error: "Field" has no attribute "allow_blank"
    error: "Field" has no attribute "allow_null"
    error: "Field" has no attribute "default"; maybe "get_default"?
    error: "Field" has no attribute "read_only"
    error: "Field" has no attribute "required"
    

    that cause a lot of headache when serializers modified dynamically.

    bug 
    opened by kalekseev 6
  • GenericAPIView has missing type parameters, but when added 'type' object is not subscriptable

    GenericAPIView has missing type parameters, but when added 'type' object is not subscriptable

    Bug report

    What's wrong

    When using mypy with strict=true, it issues the following error: Missing type parameters for generic type "GenericAPIView".

    So, I check the type and add it, but I'm now getting a runtime error: TypeError: 'type' object is not subscriptable.

    I am using django_stubs_ext.monkeypatch(), which solves the problem for other similar issues.

    I haven't test it on its own, but this should suffice, as a reproducible test:

    from rest_framework.generics import GenericAPIView
    
    class ShouldWorkView(GenericAPIView[None]):
       ...
    

    How is that should be

    The above example should pass, with no issues.

    System information

    • OS: Arch
    • python version: 3.10
    • django version: 4.0.7
    • mypy version: 0.942
    • django-stubs version: 1.12.0
    bug 
    opened by XF-FW 5
  • Bump django-stubs from 1.13.0 to 1.13.1

    Bump django-stubs from 1.13.0 to 1.13.1

    Bumps django-stubs from 1.13.0 to 1.13.1.

    Commits
    • 090aea6 Version 1.13.1 release (#1241)
    • b8a1dae [pre-commit.ci] pre-commit autoupdate (#1281)
    • 3210e2d Add Django 4.0 trigram word classes (#1278)
    • efa57fb Fix CI: Update flake8-pyi (#1279)
    • 796956a [pre-commit.ci] pre-commit autoupdate (#1275)
    • ff81496 update django.contrib.messages to use _StrOrPromise (#1274)
    • 9a34eae Type hint improvements for string promises, manager, query set (#1272)
    • fa972f1 Type ModelAdmin.fieldsets 'description' option to support gettext_lazy (#...
    • 0ae827d Add Django 4.1 constraints violation_error_message (#1263)
    • a1c192c revert changes done in #1253 that satisfy Y041, disable Y041 rule (#1256)
    • Additional commits viewable in compare view

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    dependencies python 
    opened by dependabot[bot] 4
  • protocol for new mixins

    protocol for new mixins

    It would be nice if we could use the classes already defined in generics.py as protocols.

    For example, if I want to define a new viewset mixin

    class TagModelMixin:
        @action(
            detail=True,
            methods=["PUT"],
            url_path="tag/(?P<slug>[^/.]+)",
        )
        def tag(self, request: Request, slug: str, pk: Any = None) -> Response:
            """Tag an instance with a specific tag"""
            instance = self.get_object()  
            instance.tag.add(slug)
            ...
    

    mypy complains that TagModelMixin does not have a get_object attribute

    I think the solution is to define a protocol for the api of GenericAPIView - which is sort of already defined in generics.py

    opened by janrito 0
  • Monkeypatching breaks DRF filters

    Monkeypatching breaks DRF filters

    Bug report

    What's wrong

    It appears that mokeypatching DRF viewsets (as suggested here) breaks the usage of django_filters FilterSets:

    # views.py
    class DocumentViewSet(viewsets.ModelViewSet[Document]):
        queryset = Document.objects.all()
        serializer_class = DocumentSerializer
        filterset_class = DocumentFilterSet
    
    # settings.py
    import django_stubs_ext
    from rest_framework import viewsets
    
    django_stubs_ext.monkeypatch(extra_classes=(viewsets.ModelViewSet,))
    

    With this code the DocumentViewSet completely ignores the filters defined in DocumentFilterSet. GET params simply stop working for filtering and the filter UI is completely missing from DRF's HTML view.

    Refer to this test in the demo repository. In the original commit, the test passes, but after types are added, the test fails.

    How is that should be

    DRF filters should continue working after monkeypatching.

    System information

    • OS: Ubuntu 20.04
    • python version: 3.10
    • django version: 4.1
    • mypy version: 0.991
    • django-stubs version: 1.13.0
    • django-stubs-ext version: 0.7.0
    bug 
    opened by jerivas 3
  • Conflict with Django Stubs

    Conflict with Django Stubs

    Bug report

    What's wrong

    The conflict is caused by:
        django-stubs[compatible-mypy] 1.13.0 depends on mypy>=0.980
        django-stubs[compatible-mypy] 1.13.0 depends on mypy<0.990 and >=0.980; extra == "compatible-mypy"
        djangorestframework-stubs[compatible-mypy] 1.8.0 depends on mypy>=0.980
        djangorestframework-stubs[compatible-mypy] 1.8.0 depends on mypy<0.1000 and >=0.991; extra == "compatible-mypy"
    

    How is that should be

    djangorestframework-stubs[compatible-mypy] 1.8.0 depends on mypy<0.1000 and >=0.991; extra == "compatible-mypy" Why having so much restriction about mypy package version when there is no major changes ?
    It should at least match: django-stubs[compatible-mypy] 1.13.0 depends on mypy<0.990 and >=0.980; extra == "compatible-mypy"

    System information

    • OS: Linux (Fedora 37)
    • python version: 3.11
    • django version: 4.1.3
    • mypy version: ???
    • django-stubs version: 1.8.0
    bug 
    opened by ThalusA 2
  • [Fix] Allow _StrPromise to be used in exceptions

    [Fix] Allow _StrPromise to be used in exceptions

    I have made things!

    Related issues

    I didn't create an issue, but it's the mirror of https://github.com/typeddjango/django-stubs/issues/1137, for this repo. There might be more places where the same should be applied, but this resolves my issue.

    opened by XF-FW 6
Releases(1.8.0)
  • 1.8.0(Nov 18, 2022)

    What's Changed

    • Now testing compatibility with django-stubs 1.13.0, Python 3.10 and mypy 0.991

    • Use ImmutableQueryDict for request params by @intgr in https://github.com/typeddjango/djangorestframework-stubs/pull/237

    • Make coreapi & markdown requirements optional by @intgr in https://github.com/typeddjango/djangorestframework-stubs/pull/243

    • Preserve generic in extended generic views and viewsets by @henribru in https://github.com/typeddjango/djangorestframework-stubs/pull/215

    • Add missing PageNumberPagination.get_page_number() method by @intgr in https://github.com/typeddjango/djangorestframework-stubs/pull/263

    • Fixes #230 - Add missing attributes to APIClient method Response objects by @mattwwarren in https://github.com/typeddjango/djangorestframework-stubs/pull/283

    • Introduce flake8-pyi in pre-commit checks by @hoefling in https://github.com/typeddjango/djangorestframework-stubs/pull/286

      This converts our .pyi files to follow mostly the same conventions as typeshed project, such as new | union syntax and using lowercase types dict/list.

      https://github.com/python/typeshed/blob/main/CONTRIBUTING.md#conventions

    • Add 'HEAD' to accepted HTTP verbs list by @mvandenburgh in https://github.com/typeddjango/djangorestframework-stubs/pull/249

    • Add DecimalField(normalize_output=) from DRF master by @intgr in https://github.com/typeddjango/djangorestframework-stubs/pull/294

    Continuous integration

    • Fix errors in CI by @intgr in https://github.com/typeddjango/djangorestframework-stubs/pull/273
    • Fix CI: Use flake8 from GitHub not GitLab by @intgr in https://github.com/typeddjango/djangorestframework-stubs/pull/289
    • CI: Enable testing with Python 3.10 by @intgr in https://github.com/typeddjango/djangorestframework-stubs/pull/292
    • CI: Remove unused typecheck ignores by @intgr in https://github.com/typeddjango/djangorestframework-stubs/pull/295

    Dependency updates

    • Bump types-pytz from 2022.1.0 to 2022.1.1 by @dependabot in https://github.com/typeddjango/djangorestframework-stubs/pull/240
    • Bump actions/setup-python from 3 to 4 by @dependabot in https://github.com/typeddjango/djangorestframework-stubs/pull/231
    • Bump pre-commit from 2.19.0 to 2.20.0 by @dependabot in https://github.com/typeddjango/djangorestframework-stubs/pull/241
    • Bump types-pytz from 2022.1.1 to 2022.1.2 by @dependabot in https://github.com/typeddjango/djangorestframework-stubs/pull/245
    • Update django-stubs, mypy, pytest-mypy-plugins & fix tests by @intgr in https://github.com/typeddjango/djangorestframework-stubs/pull/279
    • Update to mypy 0.991 for compatible-mypy & CI by @intgr in https://github.com/typeddjango/djangorestframework-stubs/pull/280
    • Bump types-pytz from 2022.1.2 to 2022.6.0.1 by @dependabot in https://github.com/typeddjango/djangorestframework-stubs/pull/272
    • Bump gitpython from 3.1.27 to 3.1.29 by @dependabot in https://github.com/typeddjango/djangorestframework-stubs/pull/266
    • Bump pytest from 7.1.2 to 7.2.0 by @dependabot in https://github.com/typeddjango/djangorestframework-stubs/pull/269
    • Bump djangorestframework from 3.13.1 to 3.14.0 by @dependabot in https://github.com/typeddjango/djangorestframework-stubs/pull/256
    • Version 1.8.0 release by @intgr in https://github.com/typeddjango/djangorestframework-stubs/pull/293

    New Contributors

    • @github-actions made their first contribution in https://github.com/typeddjango/djangorestframework-stubs/pull/246
    • @mattwwarren made their first contribution in https://github.com/typeddjango/djangorestframework-stubs/pull/283
    • @hoefling made their first contribution in https://github.com/typeddjango/djangorestframework-stubs/pull/286
    • @mvandenburgh made their first contribution in https://github.com/typeddjango/djangorestframework-stubs/pull/249

    Full Changelog: https://github.com/typeddjango/djangorestframework-stubs/compare/1.7.0...1.8.0

    Source code(tar.gz)
    Source code(zip)
  • v1.6.0(May 24, 2022)

  • v0.4.0(Mar 23, 2019)

  • v0.3.0(Mar 10, 2019)

  • v0.2.0(Mar 6, 2019)

Owner
TypedDjango
We make types for Django framework!
TypedDjango
Utilities for implementing a modified pre-order traversal tree in django.

django-mptt Utilities for implementing Modified Preorder Tree Traversal with your Django Models and working with trees of Model instances. Project hom

2.7k Jan 01, 2023
Simply integrate Summernote editor with Django project.

django-summernote Summernote is a simple WYSIWYG editor. django-summernote allows you to embed Summernote into Django very handy. Support admin mixins

Summernote 936 Jan 02, 2023
Visual DSL framework for django

Preface Processes change more often than technic. Domain Rules are situational and may differ from customer to customer. With diverse code and frequen

Dmitry Kuksinsky 165 Jan 08, 2023
Quick example of a todo list application using Django and HTMX

django-htmx-todo-list Quick example of a todo list application using Django and HTMX Background Modified & expanded from https://github.com/jaredlockh

Jack Linke 54 Dec 10, 2022
Basic Form Web Development using Python, Django and CSS

thebookrain Basic Form Web Development using Python, Django and CSS This is a basic project that contains two forms - borrow and donate. The form data

Ananya Dhulipala 1 Nov 27, 2021
Django Query Capture can check the query situation at a glance, notice slow queries, and notice where N+1 occurs.

django-query-capture Overview Django Query Capture can check the query situation at a glance, notice slow queries, and notice where N+1 occurs. Some r

GilYoung Song 80 Nov 22, 2022
Projeto onde podes inserir notícias, ver todas as notícias guardas e filtrar por tag. A base de dados usada é o mongoDB.

djangoProject Projeto onde podes inserir notícias, ver todas as notícias guardas e filtrar por tag. A base de dados usada é o mongoDB. packages utiliz

Sofia Rocha 1 Feb 22, 2022
Django's class-based generic views are awesome, let's have more of them.

Django Extra Views - The missing class-based generic views for Django Django-extra-views is a Django package which introduces additional class-based v

Andy Ingram 1.3k Jan 04, 2023
Django Login Api With Python

How to run this project Download and extract this project Create an environment and install all the libraries from requiements.txt pip freeze -r requi

Vikash Kisku 1 Dec 10, 2021
A simple Django dev environment setup with docker for demo purposes for GalsenDev community

GalsenDEV Docker Demo This is a basic Django dev environment setup with docker and docker-compose for a GalsenDev Meetup. The main purposes was to mak

3 Jul 03, 2021
Add infinite scroll to any django app.

django-infinite-scroll Add infinite scroll to any django app. Features - Allows to add infinite scroll to any page.

Gustavo Teixeira 1 Dec 26, 2021
A package to handle images in django

Django Image Tools Django Image Tools is a small app that will allow you to manage your project's images without worrying much about image sizes, how

The Bonsai Studio 42 Jun 02, 2022
The little ASGI framework that shines. 🌟

✨ The little ASGI framework that shines. ✨ Documentation: https://www.starlette.io/ Community: https://discuss.encode.io/c/starlette Starlette Starlet

Encode 7.7k Dec 31, 2022
Code coverage measurement for Python

Coverage.py Code coverage testing for Python. Coverage.py measures code coverage, typically during test execution. It uses the code analysis tools and

Ned Batchelder 2.3k Jan 05, 2023
This is a template tag project for django to calculate in templates , enjoy it

Calculator-Template-Django this is a template tag project for django to calculate in templates , enjoy it Get Started : 1 - Download Source Code 2 - M

1 Feb 01, 2022
Twitter Bootstrap for Django Form - A simple Django template tag to work with Bootstrap

Twitter Bootstrap for Django Form - A simple Django template tag to work with Bootstrap

tzangms 557 Oct 19, 2022
A real-time photo feed using Django and Pusher

BUILD A PHOTO FEED USING DJANGO Here, we will learn about building a photo feed using Django. This is similar to instagram, but a stripped off version

samuel ogundipe 4 Jan 01, 2020
Imparare Django ricreando un sito facsimile a quello Flask

SitoPBG-Django Imparare Django ricreando un sito facsimile a quello Flask Note di utilizzo Necessita la valorizzazione delle seguenti variabili di amb

Mario Nardi 1 Dec 08, 2021
Displaying objects on maps in the Django views and administration site.

DjangoAdminGeomap library The free, open-source DjangoAdminGeomap library is designed to display objects on the map in the Django views and admin site

Vitaly Bogomolov 31 Dec 28, 2022
Pinax is an open-source platform built on the Django Web Framework.

Symposion Pinax Pinax is an open-source platform built on the Django Web Framework. It is an ecosystem of reusable Django apps, themes, and starter pr

Pinax Project 295 Mar 20, 2022