-
-
Notifications
You must be signed in to change notification settings - Fork 121
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
request.user does not use custom User model #515
Comments
I found a solution, if anyone has a better, please tell me: from rest_framework.request import Request, wrap_attributeerrors
from django.db.models import Model
from django.http import HttpRequest
from rest_framework.generics import (
CreateAPIView,
DestroyAPIView,
GenericAPIView,
ListAPIView,
ListCreateAPIView,
RetrieveAPIView,
RetrieveDestroyAPIView,
RetrieveUpdateAPIView,
RetrieveUpdateDestroyAPIView,
UpdateAPIView,
)
from rest_framework.request import Request
from rest_framework.views import APIView
from base.db.models import CustomUser # my user model
class AuthenticatedApiRequest(Request):
@property
def user(self) -> CustomUser:
if not hasattr(self, '_user'):
with wrap_attributeerrors():
self._authenticate()
return self._user
@user.setter
def user(self, value: CustomUser) -> None:
self._user = value
self._request.user = value
T = TypeVar('T', bound=Model)
class AuthedViewMixin(APIView):
"""Mixin that types user as authenticated"""
request: AuthenticatedApiRequest
permission_classes = [IsAuthenticated]
@override
def initialize_request(self, request: HttpRequest, *args: Any, **kwargs: Any) -> Request:
"""Override to use AuthenticatedApiRequest"""
return AuthenticatedApiRequest(request, *args, **kwargs)
class ListCreateAuthedAPIView(AuthedViewMixin, ListCreateAPIView[T]):
pass
... Using the |
Thanks!
Personally, I've opted to just use |
I wonder if it is possible to solve it at all. All I can think of are workarounds. Trying to inherit from The only crutch we are left with is an assertion. |
Bug report
What's wrong
These are from the Request object in the stubbs.
However i have a different auth model defined in my
settings.py
calledCustomUser
Is there a way to get this typing correct.
Use case error:
Furthermore, if the permission classes dont allow "AnonymousUser" can we type narrow that somehow? (Like in django-stubs
How is that should be
It should be narrowed to just my
CustomUser
TL;DR:
CustomUser
instead ofAbstractBaseUser | AnonymousUser
System information
python
version: 3.11django
version: 4.2mypy
version: 1.7.1django-stubs
version: (latest)The text was updated successfully, but these errors were encountered: