[Django]-How to get mypy to recognize login_required decorator?

4👍

You can also subclass the HttpRequest and explicitly set the user field on your subclass to have the type explicitly defined as User instead of the default union pair, like so:

from django.http import HttpRequest
from my_user_app.models import MyUser

class AuthenticatedHttpRequest(HttpRequest):
    user: MyUser

Then, every time you want to use the login_required decorator, set the type hint of the request argument to your subclass (in this case it would be AuthenticatedHttpRequest) like so:

@login_required
def view(request: AuthenticatedHttpRequest) -> HttpResponse:
    if not request.user.some_attribute:
        return redirect("somewhere")
    return render(request, "template_name")

This method is specified as a recommended one in django-stubs readme file, which apparently you’re using to source the Django skeletons for mypy.

0👍

I believe casting request.user to the required type should work:

from typing import cast

@login_required
def view(request: HttpRequest) -> HttpResponse:
    request.user = cast(User, request.user)
    if not request.user.some_attribute:
        return redirect("somewhere")
    return render(request, "template_name")

Leave a comment