Skip to content

Instantly share code, notes, and snippets.

@willstott101
Last active August 4, 2018 14:29
Show Gist options
  • Save willstott101/5ff1c67d33ad5fc95f1b to your computer and use it in GitHub Desktop.
Save willstott101/5ff1c67d33ad5fc95f1b to your computer and use it in GitHub Desktop.
Simple method for using the DjangoModelPermissions permissions class on wrapped function-based views.
from rest_framework.permissions import DjangoModelPermissions
class BaseModelPerm(DjangoModelPermissions):
def has_permission(self, request, view):
perms = self.get_required_permissions(request.method, self.model)
return (
request.user and
(request.user.is_authenticated() or not self.authenticated_users_only) and
request.user.has_perms(perms)
)
def model_permissions(model_cls, base=BaseModelPerm):
from rest_framework.decorators import permission_classes
class DjangoModelPerm(base):
model = model_cls
return permission_classes((DjangoModelPerm,))
# Example:
class OperationViewSet(viewsets.ModelViewSet):
"""Operation's independent view and edit endpoint."""
queryset = (
models.Operation.objects
.filter(inventory=False)
.order_by('-scheduled_finish', '-urgency'))
serializer_class = serializers.OperationSerializer
lookup_value_regex = r'[0-9]+'
@detail_route(methods=['post'])
@model_permissions(models.Operation)
@transaction.atomic
def start(self, request, pk=None):
# I can do whatever I want because I'm ALLOWED to.
@sushifan
Copy link

sushifan commented Dec 1, 2015

Thanks a lot for providing this! How do you handle regular permissions in addition to these? For example, this doesn't work for me:
@model_permissions(models.Operation)
@permission_classes((SomeOtherCustomPermission,))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment