Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Group based permissions example / docs?

Can a kind soul point me to some good documentation or code samples on setting up group based permissions with Django? My requirements are fairly simple - I just need to enable/disable functionality based on what groups a user belongs to.

like image 798
Parand Avatar asked Oct 25 '22 20:10

Parand


1 Answers

Here is a basic example.

See: http://www.thinkjson.com/group-permissions-in-django/

First of all, say you have a model called Report.

class Report(models.Model):
    name = models.CharField(max_length=100)
    contents = models.TextField(blank=True)
    authorized_groups = models.ManyToManyField('ReportGroup', null=True, blank=True, related_name='report_groups')    
    def __str__(self):
        return self.name

You can create an intermediary model to the User model to handle group permissions:

class ReportGroup(models.Model):
    name = models.CharField(max_length=100)
    authorized_users = models.ManyToManyField(User, null=True, blank=True, related_name='report_users')
    def __str__(self):
        return self.name

Now, when you are editing a report in the Django admin, you can assign group permissions to a report. These groups can be administered as Report Groups in the Django admin, letting you select in one shot who belongs to a group.

like image 139
Todd Moses Avatar answered Jan 02 '23 20:01

Todd Moses