Skip to content

AuthenticatedHttpRequest use for LoginRequiredMixin #2046

Answered by intgr
H4rryK4ne asked this question in Q&A
Discussion options

You must be logged in to vote

Personally I never liked the AuthenticatedHttpRequest hack.

I always use explicit isinstance() guards when I need to access request.user. This adds a little runtime overhead, but is safer because it always validates the assumptions you're making. For example:

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`

Replies: 4 comments 3 replies

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
1 reply
@intgr
Comment options

intgr Apr 8, 2024
Maintainer

Comment options

You must be logged in to vote
2 replies
@mschoettle
Comment options

@intgr
Comment options

intgr Apr 9, 2024
Maintainer

Answer selected by H4rryK4ne
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants
Converted from issue

This discussion was converted from issue #1886 on April 08, 2024 16:23.