I'm working in django and got a doubt in the authentication system that, request.user work for anonymous user also or it just work only for the user who have logged in the website.I have read alot of articles but just wanted a clear answer.Also I have a custom user model.
If the user is not logged in, then request.user
will return the AnonymousUser
object [Django-doc]. It is an object where for example .is_authenticated
is False
, the primary key .pk
is None
, etc.
If the user is logged in, it will return an object from the model of your AUTH_USER_MODEL
(by default, this is the User
model [Django-doc]).
This thus makes it easy to check for example if a user is logged in with:
def some_view(request):
if request.user.is_authenticated:
# …
else:
# …
So this will not raise an error if the user is not logged in.
You can restrict a view for logged in user with @login_required
[Django-doc] decorator. This will redirect a user to the login view in case the user is not logged in.