Reputation: 282805
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?
Upvotes: 8
Views: 6106
Reputation: 10896
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))
Upvotes: 6
Reputation: 9716
It is all explained here. request.user problem was solved by using an authentication backend. I implemented a custom user according to the author's instructions and have been happy ever since.
Upvotes: 3
Reputation: 959
I think the quickest solution to your problem would simply be to call CustomUser.objects.get(user=user)
(this is assuming user is an attribute in your CustomUser model. What I would do is the following:
class CustomUser(models.Model):
user = models.ForeignKey(User, unique=True)
So when you get a queryset of CustomUsers, you can filter out the one you want based on using a filter of your user at the request.
Otherwise you can modify the middleware to include CustomUsers instead of users, but I'm not sure exactly how to do that ;)
EDIT: Mark mentioned to me that he would prefer to use inheritence so hes able to use all the custom methods of User, which makes sense and so I found an article to fix this problem nicely.
Here it is.
Upvotes: 1
Reputation: 3871
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.
Upvotes: 5