Prometheus
Prometheus

Reputation: 33625

Permissions on my Model for Django

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.

Upvotes: 3

Views: 4030

Answers (1)

Sebastian Wozny
Sebastian Wozny

Reputation: 17506

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

Upvotes: 7

Related Questions