1

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

söze
  • 500
  • 1
  • 3
  • 13

1 Answers1

1

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.

Yves Hary
  • 302
  • 1
  • 9
  • Thanks Yves. My biggest issue/use case is one person belonging to several organizations and having different rights in each. i.e read only on X in OrgA but all rights granted on X in OrgB. Would this be able to achieve that? – söze Sep 05 '20 at 09:00
  • My pleasure. If I get you right, a person can have different permissions on different objects dependend of the organization he belongs to? If so, this is beyond the abilities of djangos group system. There are third party apps outhere which could solve this problem: [look this question](https://stackoverflow.com/questions/33138477/how-to-handle-per-object-permission-in-django-nowadays#34815900) – Yves Hary Sep 07 '20 at 07:31
  • Perfect. Thank you for pointing me in this direction. Cheers! – söze Sep 07 '20 at 18:03