[Django]-Permissions on my Model for Django

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

Leave a comment