Search code examples
pythondjangodjango-authenticationdjango-auth-models

Django Extended Group's Permissions not applied to users


So I have extended Django's Group model to add an extra field like so:

class MyModel(Group):

    extra_field = models.TextField(null=True, blank=True)

On doing this, each instance of MyModel created, creates a Group instance as well. If I add a user to the resulting group with user.groups.add(group), the group is added as expected.

However, the permissions from the MyModel group do not seem to have trickled down to the user i.e

Doing user.get_all_permissions(), get_group_permissions() or even testing a user.has_permission(mygroup_permission) returns nothing. Only permissions from pure Group instances(created before extending the model) are shown.

Is there anything I need to do for permissions on customised groups to be visible on the users?

TIA


Solution

  • When you take a look in the ModelBackend, the default django authentication backend, you can see this:

    def _get_group_permissions(self, user_obj):
            user_groups_field = get_user_model()._meta.get_field('groups')
            user_groups_query = 'group__%s' % user_groups_field.related_query_name()
            return Permission.objects.filter(**{user_groups_query: user_obj})
    

    Its quite obvious, that it tries to determine the permissions from the field that represents the users groups, here groups. Because your MyModel is not tied to djangos user model, you will not get any permissions this way.

    You can now:

    1. Write a custom user model and substitute the relationship of groups
    2. Write a custom authentication backend
    3. Use a One-To-One-Relation from MyModel to Group

    In my opinion, the easiest way is to extend the Group model with a new model in an One-To-One relationship. This way you can use djangos auth system furthermore and have additional data available.