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.
You can have in your models two user classes that extend from the 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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With