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
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
Django based webapp pulling in crypto news and price data via api

Deploy Django in Production FTA project implementing containerization of Django Web Framework into Docker to be placed into Azure Container Services a

0 Sep 21, 2022
Актуальный сборник шаблонов для создания проектов и приложений на Django

О чем этот проект Этот репозиторий с шаблонами для быстрого создания Django проекта. В шаблоне проекта настроены следующий технологий: Django gunicorn

Denis Kustov 16 Oct 20, 2022
An insecure login and registration website with Django.

An insecure login and registration website with Django.

Luis Quiñones Requelme 1 Dec 05, 2021
Django Phyton Web Apps template themes

Django Phyton Web Apps template themes Free download source code project for build a modern website using django phyton web apps. Documentation instal

Mesin Kasir 4 Dec 15, 2022
Django React Project Setup

Django-React-Project-Setup INSTALLATION: python -m pip install drps USAGE: in your cmd: python -m drps Starting fullstack project with Django and Reac

Ghazi Zabalawi 7 Feb 06, 2022
Djangoblog - A blogging platform built on Django and Python.

djangoblog 👨‍💻 A blogging platform built on Django and Python

Lewis Gentle 1 Jan 10, 2022
This Django app will be used to host Source.Python plugins, sub-plugins, and custom packages.

Source.Python Project Manager This Django app will be used to host Source.Python plugins, sub-plugins, and custom packages. Want to help develop this

2 Sep 24, 2022
Simpliest django(uvicorn)+postgresql+nginx docker-compose (ready for production and dev)

simpliest django(uvicorn)+postgresql+nginx docker-compose (ready for production and dev) To run in production: docker-compose up -d Site available on

Artyom Lisovskii 1 Dec 16, 2021
Repo for All the Assignments I have to submit for Internship Application !😅

Challenges Repository for All the Assignments I have to submit for Internship Application ! 😅 As You know, When ever We apply for an Internship, They

keshav Sharma 1 Sep 08, 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
Django And React Notes App

Django & React Notes App Cloning the repository -- Clone the repository using the command below : git clone https://github.com/divanov11/Django-React

Dennis Ivy 136 Dec 27, 2022
Django Serverless Cron - Run cron jobs easily in a serverless environment

Django Serverless Cron - Run cron jobs easily in a serverless environment

Paul Onteri 41 Dec 16, 2022
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
A quick way to add React components to your Django templates.

Django-React-Templatetags This django library allows you to add React (16+) components into your django templates. Features Include react components u

Fröjd Agency 408 Jan 08, 2023
Automatically reload your browser in development.

django-browser-reload Automatically reload your browser in development. Requirements Python 3.6 to 3.10 supported. Django 2.2 to 4.0 supported. Are yo

Adam Johnson 254 Jan 04, 2023
Blog focused on skills enhancement and knowledge sharing. Tech Stack's: Vue.js, Django and Django-Ninja

Blog focused on skills enhancement and knowledge sharing. Tech Stack's: Vue.js, Django and Django-Ninja

Wanderson Fontes 2 Sep 21, 2022
Django Email Sender

Email-Sender Django Email Sender Installation 1.clone Repository & Install Packages git clone https://github.com/telman03/Email-Sender.git pip install

Telman Gadimov 0 Dec 26, 2021
Notes-Django: an advanced project to save notes in Django. where users are able to Create, Read, Update and Delete their notes.

An advanced software to keep you notes. It allows users to perform CRUD operations on theirs Notes. Was implemented Authorization and Authentication

Edilson Pateguana 1 Feb 05, 2022
Example project demonstrating using Django’s test runner with Coverage.py

Example project demonstrating using Django’s test runner with Coverage.py Set up with: python -m venv --prompt . venv source venv/bin/activate python

Adam Johnson 5 Nov 29, 2021