Whats the best way to extend Anonymous User in Django?

A simpler and more general (but less safe) solution would be to just replace django.contrib.auth.models.AnonymousUser with your own class:

class YourAnonymousUser(...):
    ...


import django.contrib.auth.models as django_auth_models
django_auth_models.AnonymousUser = YourAnonymousUser

As of 1.10.5, Django lazily imports the anonymous user class, so you won't run into issues with core Django. You also rarely interact with AnonymousUser directly, since you could just use .is_anonymous(), so you should be fine as long as you know how your dependencies use AnonymousUser.


I'm starting to think a middleware is probably the easiest solution that checks the request.user class and if is AnonymousUser then replaces it with a subclassed AnonymousUser that has the extra properties.

That sound reasonable?


Your middleware suggestion got me thinking, and I now think the best idea is to overwrite the standard AuthenticationMiddleware. That class assigns a LazyUser object to the request, which is resolved to the correct user, when accessed, by calling contrib.auth.get_user. This is probably the right place to override things, so that it calls your customised get_user function which returns your subclassed AnonymousUser.