[Django]-Why user autometically authenticated in django test case?

3๐Ÿ‘

โœ…

.is_authenticated does not mean that the user is authenticated on the server side. All User objects have is_authenticated = True, it is used to make a distinction between an User [Django-doc] object, and the AnonymousUser [Django-doc].

Indeed, by default if you look for request.user, it will either return an AnonymousUser object if there is no user attached to the setting, or a User object if the session is bound to that user.

For the builtin User model, .is_autenticated will thus always return True [GitHub]:

@property
def is_authenticated(self):
    """
    Always return True. This is a way to tell if the user has been
    authenticated in templates.
    """
    return True

You can however define your own custom user model, and define a more sophisticated test: for example only users with is_active can be authenticated, or users can only be authenticated if these have been active the last two months for example.

If you write in a view if user.is_authenticated, it will thus for the builtin user model make a distinction between an AnonymousUser (that will return False), and a User. But you can define a custom user model with a custom implementation.

Leave a comment