Search code examples
djangodjango-modelsdjango-users

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.


Solution

  • 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.