Django - User profiles of different types
Asked Answered
A

1

14

I have a Django application which allows different kinds of users: firms, administrators, external people etc. Of course all of this is easy to manage with the default authentication system and groups.

My problem is that users belonging to different groups will have different related information - for instance firms will need to provide some commercial information that does not make sense for private users. Hence I need to attach different kind of profiles, depending on the group. (In my application groups are mutually exclusive.)

Unfortunately, Django only allows a single model to be attached as a profile, and that model is declared in settings.AUTH_PROFILE_MODULE. Internally, that is retrieved by the User.get_profile() method, which basically just reads this value and performs some checks, for instance that the model actually exists.

I was thinking of subclassing User and overriding the get_profile() method, so that it returns a different model depending on the group.

Is there a simpler/cleaner way to manage different kind of profiles?

What I am proposing seems a little hack, considering that user profiles were introduced exactly to avoid having to subclass User.

Aedile answered 12/7, 2011 at 10:36 Comment(0)
L
17

Create a model with OneToOneField to User and related_name.

E. g.:

class Firm(models.Model):
    user = models.OneToOneField(User, related_name='firm')
    # other fields

class External(models.Model):
    user = models.OneToOneField(User, related_name='external')
    # other fields

Then you can check the existance of this attributes in user (if hasattr(request.user, 'firm')) and return proper instance. I'd put it in custom middleware, which would set request.user_profile for example.

Lambertson answered 12/7, 2011 at 11:0 Comment(3)
This turns out to be the simplest way. My problem now is to guarantee that these profiles are actually filled in from the admin. #6681964Aedile
This User model is not a default thing that comes with Django right? Because I get NameError: name 'User' is not defined when I try thisKnickerbockers
@JulioMarins Yes, you should import it: from django.contrib.auth.models import UserLambertson

© 2022 - 2024 — McMap. All rights reserved.