-
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 But how can this be adapted to class views with Any idea? |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 3 replies
-
You can change the type hint for the class SomeAPIView(...):
def get(self, request: AuthenticatedHttpRequest, ...) |
Beta Was this translation helpful? Give feedback.
-
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
class User(AbstractUser):
...
class AuthenticatedHttpRequest(HttpRequest):
user: User |
Beta Was this translation helpful? Give feedback.
-
Indeed. My bad. I unfortunately don't know any solution except explicitly |
Beta Was this translation helpful? Give feedback.
-
Personally I never liked the I always use explicit from django.contrib.auth.models import User
class SomeAPIView(...):
def get(self, request: HttpRequest, ...):
assert isinstance(request.user, User) # Type guard
print(request.user.email) # No error because mypy now knows the type of `request.user` |
Beta Was this translation helpful? Give feedback.
Personally I never liked the
AuthenticatedHttpRequest
hack.I always use explicit
isinstance()
guards when I need to accessrequest.user
. This adds a little runtime overhead, but is safer because it always validates the assumptions you're making. For example: