Search code examples
pythondjangodjango-guardian

Clone all object permissions in django-guardian / inherit from ForeignKey


I have an app with model hierarchy in which I need underlying objects to have the same permissions as the parent object (not only their definitions/codenames, but also per-user and per-group rights).

Django-guardian seems to have only functions allowing to check for specific user/group permissions.

Is there any canonical approach to clone all the permissions from one object to another or force the inheritance?


Solution

  • There is no way to force a permission inheritance, and there is no built-in function for copying permissions.

    In your case, you could simply check permissions against the parent object?

    Or copy the permissions explicitly. Since this comes up again and again, I've made myself a function for that purpose:

    from guardian.shortcuts import get_users_with_perms, assign_perm, get_groups_with_perms
    
    
    def copy_permissions(old_object, new_object):
        """Copy user and group permissions from one object to another."""
        for user, permissions in get_users_with_perms(old_object, attach_perms=True, with_group_users=False).items():
            for permission in permissions:
                assign_perm(permission, user, new_object)
    
        for group, permissions in get_groups_with_perms(old_object, attach_perms=True).items():
            for permission in permissions:
                assign_perm(permission, group, new_object)