Mark Cahill on Software Engineering

Group permissions in Django, sort of

If you’ve ever tried to do group permissions in the latest stable Django release (1.1.1 as of this writing), you know that it is not supported, per se. You can assign permissions to groups, and search for that permission in a view, but you can’t achieve true row-level group permissions like you can with the User model. (This is implemented in the 1.2 alpha, due to be released in March 2010).

First of all, say you have a model called Report. This is what I can relate to because I do business intelligence 90% of the time in my job.

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.