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
A music recommendation REST API which makes a machine learning algorithm work with the Django REST Framework

music-recommender-rest-api A music recommendation REST API which makes a machine learning algorithm work with the Django REST Framework How it works T

The Reaper 1 Sep 28, 2021
APIs for a Chat app. Written with Django Rest framework and Django channels.

ChatAPI APIs for a Chat app. Written with Django Rest framework and Django channels. The documentation for the http end points can be found here This

Victor Aderibigbe 18 Sep 9, 2022
Bringing together django, django rest framework, and htmx

This is Just an Idea There is no code, this README just represents an idea for a minimal library that, as of now, does not exist. django-htmx-rest A l

Jack DeVries 5 Nov 24, 2022
DRF_commands is a Django package that helps you to create django rest framework endpoints faster using manage.py.

DRF_commands is a Django package that helps you to create django rest framework endpoints faster using manage.py.

Mokrani Yacine 2 Sep 28, 2022
RestApi With Django 3.2 And Django Rest Framework

RestApi-With-Django-3.2-And-Django-Rest-Framework Description This repository is a Software of Development with Python. Virtual Using pipenv, virtuale

Daniel Arturo Alejo Alvarez 6 Aug 2, 2022
Django API without Django REST framework.

Django API without DRF This is a API project made with Django, and without Django REST framework. This project was done with: Python 3.9.8 Django 3.2.

Regis Santos 3 Jan 19, 2022
A starter template for building a backend with Django and django-rest-framework using docker with PostgreSQL as the primary DB.

Django-Rest-Template! This is a basic starter template for a backend project with Django as the server and PostgreSQL as the database. About the templ

Akshat Sharma 11 Dec 6, 2022
Atualizando o projeto APIs REST Django REST 2.0

APIs REST Django REST 3.0-KevinSoffa Atualização do projeto APIs REST Django REST 2.0-Kevin Soffa Melhorando e adicionando funcionalidades O que já fo

Kevin Soffa 2 Dec 13, 2022
Django project starter on steroids: quickly create a Django app AND generate source code for data models + REST/GraphQL APIs (the generated code is auto-linted and has 100% test coverage).

Create Django App ?? We're a Django project starter on steroids! One-line command to create a Django app with all the dependencies auto-installed AND

imagine.ai 68 Oct 19, 2022
django-dashing is a customisable, modular dashboard application framework for Django to visualize interesting data about your project. Inspired in the dashboard framework Dashing

django-dashing django-dashing is a customisable, modular dashboard application framework for Django to visualize interesting data about your project.

talPor Solutions 703 Dec 22, 2022
📊📈 Serves up Pandas dataframes via the Django REST Framework for use in client-side (i.e. d3.js) visualizations and offline analysis (e.g. Excel)

Django REST Pandas Django REST Framework + pandas = A Model-driven Visualization API Django REST Pandas (DRP) provides a simple way to generate and se

wq framework 1.2k Jan 1, 2023
Forgot password functionality build in Python / Django Rest Framework

Password Recover Recover password functionality with e-mail sender usign Django Email Backend How to start project. Create a folder in your machine Cr

alexandre Lopes 1 Nov 3, 2021
Drf-stripe-subscription - An out-of-box Django REST framework solution for payment and subscription management using Stripe

Drf-stripe-subscription - An out-of-box Django REST framework solution for payment and subscription management using Stripe

Oscar Y Chen 68 Jan 7, 2023
Django Rest Framework + React application.

Django Rest Framework + React application.

null 2 Dec 19, 2022
This is a basic Todo Application API using Django Rest Framework

Todo Application This is a basic Todo Application API using Django Rest Framework. Todo Section - User can View his previously added todo items, creat

Atharva Parkhe 1 Aug 9, 2022
Django URL Shortener is a Django app to to include URL Shortening feature in your Django Project

Django URL Shortener Django URL Shortener is a Django app to to include URL Shortening feature in your Django Project Install this package to your Dja

Rishav Sinha 4 Nov 18, 2021
django-reversion is an extension to the Django web framework that provides version control for model instances.

django-reversion django-reversion is an extension to the Django web framework that provides version control for model instances. Requirements Python 3

Dave Hall 2.8k Jan 2, 2023
Cookiecutter Django is a framework for jumpstarting production-ready Django projects quickly.

Cookiecutter Django Powered by Cookiecutter, Cookiecutter Django is a framework for jumpstarting production-ready Django projects quickly. Documentati

Daniel Feldroy 10k Dec 31, 2022
A handy tool for generating Django-based backend projects without coding. On the other hand, it is a code generator of the Django framework.

Django Sage Painless The django-sage-painless is a valuable package based on Django Web Framework & Django Rest Framework for high-level and rapid web

sageteam 51 Sep 15, 2022