request.user returning abstract user (django-stubs)

841 views Asked by At

I am trying to type the following:

user: Final[CustomUser] = self.request.user

Where CustomUser is my custom user model defined in settings.py. My IDE complains that Expected type 'CustomUser', got 'AbstractBaseUser' instead. Looking at the documentation, it says that self.request.user returns an instance of AUTH_USER_MODEL however clearly this is not happening.

Also tried:

 def get(self, request: MyRequest, *args, **kwargs) -> HttpResponse:
    user: Final[CustomUser] = self.request.user

Where

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

class MyRequest(HttpRequest):
    user: CustomUser
1

There are 1 answers

8
Iain Shelvington On BEST ANSWER

There is an open issue regarding this error here https://github.com/typeddjango/django-stubs/issues/309

According to the docs for django-stubs you have to provide your own request type when using a custom user model. At the bottom of the page on PyPi How can I use HttpRequest with custom user model?

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

class MyRequest(HttpRequest):
    user: CustomUser

Then you would have to use this to annotate self.request

 def get(self, request: MyRequest, *args, **kwargs) -> HttpResponse:
    user: Final[CustomUser] = request.user