Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - User profiles of different types

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.

like image 324
Andrea Avatar asked Jul 12 '11 10:07

Andrea


People also ask

Can I have two user models in Django?

You can have in your models two user classes that extend from the USER model.

What is Django user model?

For Django's default user model, the user identifier is the username, for custom user models it is the field specified by USERNAME_FIELD (see Customizing Users and authentication). It also handles the default permissions model as defined for User and PermissionsMixin .


1 Answers

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.

like image 181
DrTyrsa Avatar answered Sep 22 '22 13:09

DrTyrsa