Created
February 25, 2013 22:46
-
-
Save dbrgn/5034038 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
def is_owner_or_readonly(fieldname='owner'): | |
"""Function to generate a permission class that checks whether the current | |
user is the owner according to the specified field name.""" | |
class IsOwnerOrReadOnly(permissions.BasePermission): | |
"""Only allow owners of an object to edit it.""" | |
def has_object_permission(self, request, view, obj): | |
# Read permissions are allowed to any request, | |
# so we'll always allow GET, HEAD or OPTIONS requests. | |
if request.method in permissions.SAFE_METHODS: | |
return True | |
# Write permissions are only allowed to the owner of the snippet | |
return getattr(obj, fieldname) == request.user | |
return IsOwnerOrReadOnly |
This file contains hidden or 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
class QuoteDetail(generics.RetrieveUpdateAPIView): | |
model = models.Quote | |
serializer_class = serializers.QuoteSerializer | |
permission_classes = ( | |
custom_permissions.is_owner_or_readonly('author'), | |
permissions.IsAuthenticated, | |
) | |
def pre_save(self, obj): | |
obj.author = self.request.user |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment