You do not have permission to perform this action when accessing api in django
Asked Answered
D

2

8

i am trying to add custom permissions in my Django app using Django rest framework. i created an API n tested it in postman it works fine for authenticated user. however it doesnt display details when i visit details view . for example when i visit http://localhost:8000/placeslist/ it displays all the places but when i try http://localhost:8000/placeslist/1/ it says you dont have permission. i dont know where i went wrong

models.py

class Places(BaseModel):
  name = models.CharField(max_length=255,null=True,default='')
  owner=models.ForeignKey('auth.User',related_name='place_list',on_delete=models.CASCADE,null=True)    

Views.py

class PlacesView(generics.ListCreateAPIView):
    queryset = Places.objects.all()
    serializer_class = PlacesSerializer
    permission_classes = (permissions.IsAuthenticated, IsOwner)

    def perform_create(self,serializer):
      serializer.save(owner=self.request.user)


class PlacesDetailView(generics.RetrieveUpdateDestroyAPIView):
    queryset = Places.objects.all()
    serializer_class = PlacesSerializer
    permission_classes = (permissions.IsAuthenticated, IsOwner)

Permission.py

class IsOwner(BasePermission):
  def has_object_permission(self, request, view, obj):
    if isinstance(obj, Places):
        return obj.owner == request.user       
    return obj.owner == request.user    

Serializer.py

class PlacesSerializer(serializers.ModelSerializer):
  owner = serializers.ReadOnlyField(source='owner.username')
  class Meta:
    model = Places
    fields =('id','name','owner')

urls.py

url(r'^placeslist/$', PlacesView.as_view(), name="place"),
url(r'placeslist/(?P<pk>[0-9]+)/$',PlacesDetailView.as_view(), 
name="place_details"),
url(r'^get-token/', obtain_auth_token),

Settings.py

....

REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
    'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework.authentication.BasicAuthentication',
    'rest_framework.authentication.TokenAuthentication',
)
}

....
Detonator answered 20/7, 2018 at 6:55 Comment(0)
T
7

That's because of your custom permission where you a trying to access an instance (Place with pk = 1) where the owner is not the user you are currently using.

Check the owner of that Place.

And you can just remove the permissions.IsAuthenticated on your view, because you already put it in the default permission class.

Torus answered 20/7, 2018 at 7:27 Comment(1)
make sure your settings DEFAULT_PERMISSION_CLASSES are set properly in settings.py fileCheree
J
0

In my case, I didn't link my new ViewSet in urls.py so the request was going to some other API which had a different permission class. You can put a debugger in restframework's code and see what happens.

Jillayne answered 19/12, 2023 at 9:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.