2014-06-09

How is_authenticated() is done in Django?


I tried to understand how is_authenticated() is done in Django, so I did a code search in Django's GitHub repository and found two definitions of it in django/contrib/auth/models.py as shown below:


I am surprised that one definition always return true, while the other always return false, as I was expecting some sort of logic to check if a user is logged or not.

Turn out it is simpler than that. The is_authenticated() method is bound to either a User object or an AnonymousUser object. So at the time is_authenticated() is called, it already knows whether the user is authenticated or not by the type of the object.

Neat.

No comments: