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
Projeto Crud Django and Mongo

Projeto-Crud_Django_and_Mongo Configuração para rodar o projeto Download Project

Samuel Fernandes Oliveira 2 Jan 24, 2022
Declarative model lifecycle hooks, an alternative to Signals.

Django Lifecycle Hooks This project provides a @hook decorator as well as a base model and mixin to add lifecycle hooks to your Django models. Django'

Robert Singer 1k Dec 31, 2022
Dynamic Django settings.

Constance - Dynamic Django settings A Django app for storing dynamic settings in pluggable backends (Redis and Django model backend built in) with an

Jazzband 1.5k Jan 07, 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
Simple API written in Python using FastAPI to store and retrieve Books and Authors.

Simple API made with Python FastAPI WIP: Deploy in AWS with Terraform Simple API written in Python using FastAPI to store and retrieve Books and Autho

Caio Delgado 9 Oct 26, 2022
Agenda feita usando o django para adicionar eventos

Agenda de Eventos Projeto Agenda com Django Inicio O projeto foi iniciado no Django, usando o models.py foi adicionado os dados dos eventos e feita as

Bruno Fernandes 1 Apr 14, 2022
Logan is a toolkit for building standalone Django applications

Logan Logan is a toolkit for running standalone Django applications. It provides you with tools to create a CLI runner, manage settings, and the abili

David Cramer 206 Jan 03, 2023
Official clone of the Subversion repository.

Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. All documentation is in the "docs" directo

Raymond Penners 3 May 06, 2022
Money fields for Django forms and models.

django-money A little Django app that uses py-moneyed to add support for Money fields in your models and forms. Django versions supported: 1.11, 2.1,

1.4k Jan 06, 2023
Custom Django field for using enumerations of named constants

django-enumfield Provides an enumeration Django model field (using IntegerField) with reusable enums and transition validation. Installation Currently

5 Monkeys 195 Dec 20, 2022
No effort, no worry, maximum performance.

Django Cachalot Caches your Django ORM queries and automatically invalidates them. Documentation: http://django-cachalot.readthedocs.io Table of Conte

NoriPyt 980 Jan 06, 2023
This is raw connection between redis server and django python app

Django_Redis This repository contains the code for this blogpost. Running the Application Clone the repository git clone https://github.com/xxl4tomxu9

Tom Xu 1 Sep 15, 2022
With Django Hijack, admins can log in and work on behalf of other users without having to know their credentials.

Django Hijack With Django Hijack, admins can log in and work on behalf of other users without having to know their credentials. Docs 3.x docs are avai

1.2k Jan 05, 2023
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
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
this is a simple backend for instagram with python and django

simple_instagram_backend this is a simple backend for instagram with python and django it has simple realations and api in 4 diffrent apps: 1-users: a

2 Oct 20, 2021
Buckshot++ is a new algorithm that finds highly stable clusters efficiently.

Buckshot++: An Outlier-Resistant and Scalable Clustering Algorithm. (Inspired by the Buckshot Algorithm.) Here, we introduce a new algorithm, which we

John Jung 1 Jul 02, 2022
Django models and endpoints for working with large images -- tile serving

Django Large Image Models and endpoints for working with large images in Django -- specifically geared towards geospatial tile serving. DISCLAIMER: th

Resonant GeoData 42 Dec 17, 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
Cached file system for online resources in Python

Minato Cache & file system for online resources in Python Features Minato enables you to: Download & cache online recsources minato supports the follo

Yasuhiro Yamaguchi 10 Jan 04, 2023