Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: use custom class for request.user?

Tags:

django

I've extended Django's default user class like this:

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

But now I want to use that everywhere instead of the default User class. In my view methods, I have access to request.user but that's an instance of the User class. What's the easiest way to make it return a CustomUser instead?

like image 493
mpen Avatar asked Nov 11 '09 22:11

mpen


2 Answers

you can also "monkey patch" the 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))
like image 138
Evgeny Avatar answered Sep 28 '22 00:09

Evgeny


I'm not sure if you can do that exactly, but you can access your CustomUser attributes using the Django user_profile feature.

In your settings.py:

AUTH_PROFILE_MODULE = 'myapp.CustomUser'

In your view:

user_friends = user.get_profile().friends

Check out this link for more info.

like image 30
hora Avatar answered Sep 28 '22 00:09

hora