alias51
alias51

Reputation: 8648

How to assign Group permissions to individual records in Django

I have a model in which I would like to assign specific records to a user group (or several user groups), so that an individual record is editable/viewable only by members of those groups associated with it.

I want the user who creates a record in the model to be able to assign the group permissions for that record.

What's the best way to do this? E.g. can I assign a OneToMany field? Something like:

from django.contrib.auth.models import Group, Permission

class MyModel(models.Model):
    title = models.CharField(max_length=200, null=True)
    groups = [ What comes next? ]

Upvotes: 1

Views: 653

Answers (1)

cagrias
cagrias

Reputation: 1847

You want to apply object-level permissions and the common approach to do that is to assign a ForeignKey to a Group. So that each object will have a single Group and groups can have more than one MyModel objects. Here is an example:

# models.py
from django.contrib.auth.models import Group, Permission

class MyModel(models.Model):
    title = models.CharField(max_length=200, null=True)
    groups = models.ForeignKey(Group, on_delete=models.CASCADE)

You can do the object-level permission by:

def my_view(request):
    filtered_objects = models.MyModel.objects.filter(groups=request.user.groups)

Upvotes: 2

Related Questions