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
Radically simplified static file serving for Python web apps

WhiteNoise Radically simplified static file serving for Python web apps With a couple of lines of config WhiteNoise allows your web app to serve its o

Dave Evans 2.1k Dec 15, 2022
A Django backed for PostgreSQL using Psycopg 3

A Django backend for PostgreSQL using Psycopg 2 The backend passes the entire Django test suite, but it needs a few modifications to Django and to i

Daniele Varrazzo 42 Dec 16, 2022
Integarting Celery with Django to asynchronous tasks 📃

Integrating 🔗 Celery with Django via Redis server ,To-Do asynchronously 👀task without stopping the main-flow 📃 of Django-project . It increase your speed 🚀 and user experience 🤵 of website

Rushi Patel 4 Jul 15, 2022
AUES Student Management System Developed for laboratory works №9 Purpose using Python (Django).

AUES Student Management System (L M S ) AUES Student Management System Developed for laboratory works №9 Purpose using Python (Django). I've created t

ANAS NABIL 2 Dec 06, 2021
Django + NextJS + Tailwind Boilerplate

django + NextJS + Tailwind Boilerplate About A Django project boilerplate/templa

Shayan Debroy 3 Mar 11, 2022
Backend with Django .

BackendCode - Cookies Documentation: https://docs.djangoproject.com/fr/3.2/intro/ By @tcotidiane33 & @yaya Models Premium class Pack(models.Model): n

just to do it 1 Jan 28, 2022
Awesome Django Blog App

Awesome-Django-Blog-App Made with love django as the backend and Bootstrap as the frontend ! i hope that can help !! Project Title Django provides mul

ANAS NABIL 2 Feb 08, 2022
Built from scratch to replicate some of the Django admin functionality and add some more, to serve as an introspective interface for Django and Mongo.

django-mongonaut Info: An introspective interface for Django and MongoDB. Version: 0.2.21 Maintainer: Jazzband (jazzband.co) This Project is Being Mov

Jazzband 238 Dec 26, 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
Django datatables with htmx.

Django datatables with htmx.

Regis Santos 7 Oct 23, 2022
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
Use watchfiles in Django’s autoreloader.

django-watchfiles Use watchfiles in Django’s autoreloader. Requirements Python 3.7 to 3.10 supported. Django 2.2 to 4.0 supported. Installation Instal

Adam Johnson 43 Dec 14, 2022
A standalone package to scrape financial data from listed Vietnamese companies via Vietstock

Scrape Financial Data of Vietnamese Listed Companies - Version 2 A standalone package to scrape financial data from listed Vietnamese companies via Vi

Viet Anh (Vincent) Tran 45 Nov 16, 2022
Redia Cache implementation in django.

django-redis Recipe APP Simple Recipe app which shows different kinds off recipe to the user. Why Cache ? Accessing data from cache is much faster tha

Avinash Alanjkar 1 Sep 21, 2022
Log and View requests made on Django

Django Request Viewer Log and view requests made on your Django App Introduction Recently, @ichtrojan and @toniastro released horus, a request logger

Akere Mukhtar 26 May 29, 2022
Coltrane - A simple content site framework that harnesses the power of Django without the hassle.

coltrane A simple content site framework that harnesses the power of Django without the hassle. Features Can be a standalone static site or added to I

Adam Hill 58 Jan 02, 2023
WeatherApp - Simple Python Weather App

Weather App Please star this repo if you like ⭐ It's motivates me a lot! Stack A

Ruslan Shvetsov 3 Apr 18, 2022
PostgreSQL with Docker + Portainer + pgAdmin + Django local

django-postgresql-docker Running PostgreSQL with Docker + Portainer + pgAdmin + Django local for development. This project was done with: Python 3.9.8

Regis Santos 4 Jun 12, 2022
A simple trivia quizzz web app made using django

Trivia Quizzz A simple trivia quizzz web app made using django Demo http://triviaquizzz.herokuapp.com/ & https://triviaquiz.redcrypt.xyz Features Goog

Rachit Khurana 2 Feb 10, 2022
A ToDO Rest API using Django, PostgreSQL and Docker

This Rest API uses PostgreSQL, Docker and Django to implements a ToDo application.

Brenno Lima dos Santos 2 Jan 05, 2022