[Fixed]-Whats the best way to extend Anonymous User in Django?

14πŸ‘

βœ…

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.

5πŸ‘

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.

πŸ‘€Blender

2πŸ‘

The best way is to use a python package (or write your own) which will swap Django default AnonymousUser class with your own class. You can implement a middleware for this (I think it’s the best place).

For example, you can use django-custom-anonymous to provide customization of AnonymousUser. Also you can find it on pypi.

πŸ‘€bugov

1πŸ‘

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?

πŸ‘€Ross

0πŸ‘

You could probably use django-rest-framework which allows you to customise AnonymousUser through UNAUTHENTICATED_USER in settings likes this

REST_FRAMEWORK = {
    'UNAUTHENTICATED_USER': 'application.AnonymousUser',
}

Keep in mind that this user class will only be available from DRF views

πŸ‘€Radical Ed

-1πŸ‘

You should subclass or create a model that has a one to one relationship with the AnonymousUser class.

Leave a comment