Zeinab Mohammed
Zeinab Mohammed

Reputation: 63

permission_classes doesn't work whats going wrong?

I made acustom permission which make only advertise creator can delete or edit it ,though permissions have no effect and alraedy deleted another user advertise what;s going wrong here?

views.py:

from rest_framework import permissions,generics
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from .permissions import IsOwnerOrReadOnly
from advertise.serializers import AdSerializer

class AdListGeneric(generics.ListCreateAPIView):
    permission_classes([permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly],)
    queryset=Advertise.objects.all()
    serializer_class=AdSerializer

# @permission_classes([permissions.IsAuthenticatedOrReadOnly],[IsOwnerOrReadOnly])
class AdDetailgeneric(generics.RetrieveUpdateDestroyAPIView):
    permission_classes([permissions.IsAuthenticatedOrReadOnly,IsOwnerOrReadOnly],)
    queryset=Advertise.objects.all()
    serializer_class=AdSerializer
,,,

permissions.py:

from rest_framework import permissions
class IsOwnerOrReadOnly(permissions.BasePermission):
    """
    create custom permission allow only owner to edit it
    """
    def has_object_permission(self, request,view, obj):
        #read allowd to all users
        #so we always allow GET, HEAD, OPTioNS
        if request.method in permissions.SAFE_METHODS:
            return True
        #write permissions only for allwed users:
        return obj.publisher == request.user
,,

,

Upvotes: 0

Views: 622

Answers (1)

natka_m
natka_m

Reputation: 1612

permission_classes has to be a class attribute, and has to be an iterable (e.g. a tuple or a list). See how it is used in the get_permissions method in the ListCreateAPIView:

def get_permissions(self):
    """
    Instantiates and returns the list of permissions that this view requires.
    """
    return [permission() for permission in self.permission_classes]

Therefore, your views should look like this:

class AdListGeneric(generics.ListCreateAPIView):
    permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly]
    ...

Upvotes: 1

Related Questions