Hi! I am new to Django and still trying to understand the best-practices and patterns. I wonder if anyone has any suggestions for type-hinting custom User
models so that I don’t get a bunch of warnings when I access them through request.user
?
For instance if I have a simple model like this:
# models.py
class User(AbstractUser):
is_special_user = models.BooleanField(default=False)
which inherits from AbstractUser
, which itself inherits from AbstractBaseUser
, I get a lot of warnings (I use VSCode) when I try and access the request.user
and use it in any functions that require a User
. For instance in something like this:
# views.py
def my_func(user: User) -> None:
print(user.is_special_user)
@login_required
def my_view(request: WSGIRequest) -> None:
my_func(request.user)
I get warnings about how:
Argument of type "AbstractBaseUser | AnonymousUser" cannot be assigned to parameter "user" of type "User" in function "my_func"
"AbstractBaseUser | AnonymousUser" is not assignable to "User"
Pylance[reportArgumentType]
(https://github.com/microsoft/pyright/blob/main/docs/configuration.md#reportArgumentType)
(variable) user: AbstractBaseUser
I suppose this might be a VSCode specific issue, and not something Django related necessarily? But I wonder if anyone has found any good methods for avoiding these warnings and ensuring that user is typed properly?
The best I have come up with so far is to just create a wrapper function, and use # type: ignore
to mask out the warnings… but I assume there is a better way to handle this?
def get_user(request: WSGIRequest) -> User:
return request.user # type: ignore
thanks so much for any advice or suggestions!
best,
@ed-p-may