[Answer]-Django Auth: Permissions for model-based category

1๐Ÿ‘

โœ…

I really like django-guardian (https://github.com/lukaszb/django-guardian.git) for this kind of stuff. It provides object-level permissions for Django.

The way I would approach your specific problem is the following.

Define the actions that the owners of companies are allowed to complete

class Meta:
    permissions = [('can_add', 'Add product to company'), etc...]

Next I would create a group for each company on creation of a new company, by adding into the save().

def save():
    # Create a permission group named %s_group % company_name
    # assign(permission, group) - add the permissions to this group.

At this point with your example you would have Foo_group, and Bar_group, and the permissions of those objects assigned to the groups.

Now all you have left to do is add / remove users from different company groups to grant them the permissions associated with those objects.

The last component of this is checking for the permissions with the associated actions. This can be done in the appropriate views for each of the actions eg. adding, removing, etc.

I prefer class-based views because it is really nice to use Mixins for the permission checking. Guardian comes with an out of the box PermissionRequiredMixin, but usually something custom works for more complex situations.

๐Ÿ‘คjondykeman

Leave a comment