3

I have a model called Logs:

class Logs(models.Model):
    entry = models.CharField(max_length=100)

Some Users can administer logs, others edit and the rest only view. How would you handle such permissions in Django?

I was thinking of adding a new many-to-many field, one for admins the other for editors, then on the save function check which user is in what group.

However, this seems static and bad, can I somehow use Django's built in permissions? What other solutions, packages are there, what is the best approach to this problem?

I have seen you can create custom permissions in Django i.e.

permission = Permission.objects.create(codename='can_publish',
                                       name='Can Publish Logs',
                                       content_type=content_type)

But how on Logs would I check the permissions, would this be done in the Save() method.

3

1 Answer 1

7

You're asking for permissions functionality which is implemented for you in django.contrib.auth.

In particular you would like to control who can edit a model, which is included in the default permissions of django. You can also implement custom permissions if you need to.

You would check these privileges on the views and django.contrib.auth provides the permission_required decorator. Which does what you require.

You do not need to reimplement the many to many field for editors admins and users either. You can use django.contrib.auth Group to add your users to the respective group and then assign permissions to the groups:

from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
from api.models import Logs
new_group, created = Group.objects.get_or_create(name='new_group')
ct = ContentType.objects.get_for_model(Logs)

permission = Permission.objects.create(codename='can_clean_logs',
                                   name='Can clean logs',
                                   content_type=ct)
new_group.permissions.add(permission)

Check django-guardian for more fine-grained control and object-level permissions.

django-rest-framework provides a hook for permissions and provides a integration of django model permissions.

The following answer can also be helpful:

User Groups and permissions

2
  • +1 for Django-guardian. Though you may not need another dependency for one class and can implement permissions yourself.
    – fiacre
    Commented Jun 1, 2015 at 13:39
  • I don't see anywhere in guardian docs on how it applies model-level permissions. It seems to follow the same paradigm of setting permissions at the view and template levels.
    – AlxVallejo
    Commented Apr 11 at 15:35

Not the answer you're looking for? Browse other questions tagged or ask your own question.