Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the best way to extend Anonymous User in Django?

I want to make my User objects all have the same base behaviour and to do so I need to add a couple of methods / properties to Anonymous User.

I've already subclassed User to make richer user objects but I was wondering if anyone has done the same for Anonymous User? And if there are any preferred ways of doing it!

like image 960
Ross Avatar asked May 11 '10 07:05

Ross


People also ask

How does Django find anonymous users?

You can check if request. user. is_anonymous returns True . Seems like in Django 1.9 it is rather is_authenticated() : please see docs.djangoproject.com/en/1.9/topics/auth/default/…

What is Get_user_model Django?

Method 3 – get_user_model() : The other way to reference the user model is via get_user_model which returns the currently active user model: either a custom user model specificed in AUTH_USER_MODEL or else the default built-in User.

What is abstract user in Django?

AbstractUser class inherits the User class and is used to add Additional Fields required for your User in Database itself. SO its change the schema of the database. It is basically used to add fields like date_of_birth , location and bio etc. to the existing User model This is Done to the very Beginning of the project.


2 Answers

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.

like image 130
Daniel Roseman Avatar answered Oct 26 '22 10:10

Daniel Roseman


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.

like image 30
Blender Avatar answered Oct 26 '22 10:10

Blender