Last active
August 4, 2018 14:29
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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,))