django-guardian support for Django REST Framework
Low maintenance activity. Last release 17 months ago, commits in 0 of the last 26 weeks. Weaker on commit activity and recent releases.
pip install djangorestframework-guardiandjango-rest-framework-guardian
django-rest-framework-guardian provides django-guardian integrations for Django REST Framework.
Installation & Setup
To use django-rest-framework-guardian, install it into your environment.
$ pip install djangorestframework-guardian
Ensure both Django REST Framework and django-guardian are configured and added to your INSTALLED_APPS setting.
INSTALLED_APPS = [
'rest_framework',
'guardian',
]
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend',
'guardian.backends.ObjectPermissionBackend',
]
ObjectPermissionsFilter
The filter will ensure that querysets only returns objects for which the user has the appropriate view permission.
If you're using ObjectPermissionsFilter, you'll probably also want to add an appropriate object permissions
class, to ensure that users can only operate on instances if they have the appropriate object permissions. The easiest
way to do this is to subclass DjangoObjectPermissions and add 'view' permissions to the perms_map attribute.
An example using both ObjectPermissionsFilter and DjangoObjectPermissions might look like the following:
permissions.py:
from rest_framework import permissions
class CustomObjectPermissions(permissions.DjangoObjectPermissions):
"""
Similar to `DjangoObjectPermissions`, but adding 'view' permissions.
"""
perms_map = {
'GET': ['%(app_label)s.view_%(model_name)s'],
'OPTIONS': ['%(app_label)s.view_%(model_name)s'],
'HEAD': ['%(app_label)s.view_%(model_name)s'],
'POST': ['%(app_label)s.add_%(model_name)s'],
'PUT': ['%(app_label)s.change_%(model_name)s'],
'PATCH': ['%(app_label)s.change_%(model_name)s'],
'DELETE': ['%(app_label)s.delete_%(model_name)s'],
}