Skip to content

error: "HttpRequest" has no attribute "user" #70

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

Closed
snoepkast opened this issue Apr 23, 2019 · 3 comments · Fixed by #109
Closed

error: "HttpRequest" has no attribute "user" #70

snoepkast opened this issue Apr 23, 2019 · 3 comments · Fixed by #109

Comments

@snoepkast
Copy link

Hi there,

I have the following code:

class MyView(RedirectView):
    def get_redirect_url(self, *args: Any, **kwargs: Any) -> Optional(str):
        if self.request.user.is_authenticated():
            do_something_with_user()

Which results in:

$ mypy
> api/users/authentication/views.py:28: error: "HttpRequest" has no attribute "user"

Which is probably because the HttpRequest class doesn't really have the user but it is almost always added through the authentication middleware (either User or AnonymousUser).

So how do I fix this?

@PeterJCLaw
Copy link
Contributor

It would be great to have a general solution for this -- Django has several things which are added by middleware (the other one which immediately springs to mind is the session attribute).

@Yobmod
Copy link

Yobmod commented Jul 19, 2019

I don't know if it makes sense to do, but I tried changing my request type to WSGIRequest, which subclasses HTTPRequest and adds a user attribute (as AbstractUser).
It silenced the error at least....

@mkurnikov
Copy link
Member

It could be added as a plugin, like, "if some AuthenticationMiddleware", add user to some HttpRequest". We need some way to describe this fact in the middleware class.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging a pull request may close this issue.

4 participants