User can update or delete data which created by others

28
November 21, 2019, at 7:50 PM
class StoryViewSet(viewsets.ModelViewSet):
    serializer_class = StorySerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)

I have viewset with all CRUD functions. The problem is that user can edit or delete stories of another user, I found DjangoModelPermissionsOrAnonReadOnly in permissions, but I cannot even create. I am using author as foreign key in Storymodel. Also I am using rest_framework.authtoken. So, I think there is two options, create own permission or rewrite some permission. Which one is better?

Answer 1

Write a customer object-level permission. Here is an example:

class IsOwnerOrReadOnly(permissions.BasePermission):
    """
    Object-level permission to 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
        return obj.author == request.user

And include it to permission_classes list.

Answer 2

you can also add a perform_update function in your views.

 def perform_update(self, serializer):
        instance = serializer.save(author=self.request.user)
READ ALSO
how crop image from selection 4 points on mouse click event using PyQt5? [on hold]

how crop image from selection 4 points on mouse click event using PyQt5? [on hold]

I want to crop a image in such a way that i'll click on 4 points and that 4 for points will join and draw a rectangle or square and crop that part of image in python using PyQt5

42
None to NULL conversion in Pyodbc executemany operation taking too long

None to NULL conversion in Pyodbc executemany operation taking too long

I have a list of tuples with some None values, which are to be inserted to the database as NULL valuesHowever, while working on just 30,000 records, it is taking 3 minutes to run the insert query

30
Passing values from command line python

Passing values from command line python

I have a python function that requires several parametersSomething like:

50
Is it a good idea to run multiple loops and .find() pymongo command to render homepage? [on hold]

Is it a good idea to run multiple loops and .find() pymongo command to render homepage? [on hold]

This question is focused more on the best development practice

24