In Django why is the is_authenticated method always returns True?

4

I saw that in the documentation it indicates the is_authenticated method as being responsible for telling the templates if there is a logged in user. I also saw in the method code that it contains only the following:

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

So I do not understand how the system knows if the user is logged in. What is the meaning of this method always returning True?

    
asked by anonymous 19.02.2015 / 01:09

1 answer

3

Quick response

This method appears in models.AnonymousUser and models.User, whereas User objects will only exist if you are authenticated, otherwise you will have an instance of AnonymousUser with default attributes.

Long Answer

Django has a modeling that allows to abstract the visitor to two levels, anonymous user or a person of the system (user), when you are talking about anonymous user is any person that is accessing, by default it contains the following configuration :

  • id and always None.
  • is_staff and is_superuser are always False.
  • is_active and always False.
  • groups and user_permissions are always empty.
  • is_anonymous () returns True instead of False
  • is_authenticated () returns False instead of True.
  • set_password (), check_password (), save (), and delete () generate exception
  • NotImplementedError.

What is implemented by models.AnonymousUser

class AnonymousUser(object):
    id = None
    pk = None
    username = ''
    is_staff = False
    is_active = False
    is_superuser = False
    _groups = EmptyManager(Group)
    _user_permissions = EmptyManager(Permission) 

See rest here ....

If the user exists (authenticated), it becomes an instance of models.User , which in turn inherits from AbstractUser which in turn inherits from AbstractBaseUser where the is_authenticated method is found, AbstractUser also inherits from PermissionsMixin, who populates Users and makes the call to is_authenticated is AuthenticationMiddleware see source in github's code

class User(AbstractUser):
    """
    Users within the Django authentication system are represented by this
    model.
    Username, password and email are required. Other fields are optional.
    """
    class Meta(AbstractUser.Meta):
        swappable = 'AUTH_USER_MODEL'

See the rest here ...

Look at this example application, is_authenticated is a user method.

if request.user.is_authenticated():
    # Instancia class models.User, existe por que está autenticado
else:
    # Instancia AnonymousUser
    
19.02.2015 / 01:52