Django: use custom class for request.user?

I extended the default user class of Django as follows:

class CustomUser(User): friends = models.ManyToManyField('self', symmetrical=False) 

But now I want to use this everywhere, not the default User class. In my opinion, I have access to request.user , but this is an instance of the User class. What is the easiest way to get it to return CustomUser instead?

+6
django
source share
4 answers

you can also "neutralize the patch" with an existing user model somewhere in your models.py, and it should just work. In your code, just keep using the original class.

 User.add_to_class('friends',models.ManyToManyField('self', symmetrical=False)) 
+6
source share

I'm not sure you can do this for sure, but you can access your CustomUser attributes using the Django user_profile function.

In your settings.py file:

 AUTH_PROFILE_MODULE = 'myapp.CustomUser' 

In your opinion:

 user_friends = user.get_profile().friends 

Refer to this link for more information.

+5
source share

Everything is explained here . The request.user problem has been resolved using an authentication backend. I implemented the user user according to the instructions of the author and have been happy ever since.

+3
source share

I think the fastest solution to your problem would be to simply call CustomUser.objects.get(user=user) (this assumes the user is an attribute in your CustomUser model. I would do the following:

 class CustomUser(models.Model): user = models.ForeignKey(User, unique=True) 

Therefore, when you receive a request to select CustomUsers, you can filter out the one you want based on using your user's filter on request.

Otherwise, you can change the middleware to include CustomUsers instead of users, but I don’t know exactly how to do this;)

EDIT: Mark mentioned to me that he would prefer to use inheritance, so he could use all user methods of the user, which makes sense, and so I found an article to fix this problem.

Here it is.

+1
source share

All Articles