django-stubs icon indicating copy to clipboard operation
django-stubs copied to clipboard

AuthenticatedHttpRequest use for LoginRequiredMixin

Open H4rryK4ne opened this issue 2 years ago • 1 comments

As described in https://github.com/typeddjango/django-stubs#how-can-i-create-a-httprequest-thats-guaranteed-to-have-an-authenticated-user one could use AuthenticatedHttpRequest annotate request in function views with @login_required decorators.

But how can this be adapted to class views with LoginRequiredMixin?

Any idea?

H4rryK4ne avatar Dec 22 '23 11:12 H4rryK4ne

You can change the type hint for the request argument to AuthenticatedHttpRequest.

class SomeAPIView(...):
    def get(self, request: AuthenticatedHttpRequest, ...)

mschoettle avatar Jan 12 '24 17:01 mschoettle

Sorry for the late reply ...

Finally I got to the point to refactor my app and to try your solution. But I get the following error message from mypy v1.8.0

my_app/views/__init__.py:70: error: Argument 1 of "get" is incompatible with supertype "ProcessFormView"; supertype defines the argument type as "HttpRequest"  [override]
        def get(self, request: AuthenticatedHttpRequest, *args: Any, **kwargs: Any) -> HttpResponse:
                      ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class User(AbstractUser):
    ...

class AuthenticatedHttpRequest(HttpRequest):
    user: User

H4rryK4ne avatar Mar 06 '24 13:03 H4rryK4ne

Indeed. My bad.

I unfortunately don't know any solution except explicitly cast()ing request to an authenticated_request in the method body.

mschoettle avatar Apr 08 '24 16:04 mschoettle