Skip to content

as_view always returns a callable that returns a base response, which is not specific enough #2873

@samueljsb

Description

@samueljsb

Bug report

What's wrong

The return type of as_view is always a def (*Any, **Any) -> django.http.response.HttpResponseBase, so the response returned from the view function is always django.http.response.HttpResponseBase. This means that several attributes are missing from, for example, a template response:

from typing import reveal_type

from django.views.generic import TemplateView
from django.test import RequestFactory


class MyView(TemplateView):
    template_name = "template.html"


rf = RequestFactory()
request = rf.get("/")

view = MyView.as_view()
reveal_type(view)

response = view(request)
reveal_type(response)

print(response.rendered_content)
$ mypy t.py
t.py:13: note: Revealed type is "def (*Any, **Any) -> django.http.response.HttpResponseBase"
t.py:16: note: Revealed type is "django.http.response.HttpResponseBase"
t.py:18: error: "HttpResponseBase" has no attribute "rendered_content"  [attr-defined]
Found 1 error in 1 file (checked 1 source file)

How is that should be

Calling as_view on a TemplateView returns a function that returns a django.template.response.TemplateResponse. The type checker should know this.

System information

  • OS: macOS 15.7
  • python version: 3.13.7
  • django version: 5.2.7
  • mypy version: 1.18.2
  • django-stubs version: 5.2.7
  • django-stubs-ext version: 5.2.7

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions