3
votes

Suppose I have the following model -

class Person(models.Model):
name = models.CharField(max_length=200)
clubs = models.ManyToManyField(Club,related_name = 'people')
date = models.DateTimeField(default=datetime.now)

def __str__(self):
    return self.name

used to create a rest api.

views.py

class PersonDetail(generics.RetrieveUpdateDestroyAPIView):
    serializer_class = PersonSerializer

    def get_object(self):
        person_id = self.kwargs.get('pk',None)
        return Person.objects.get(pk=person_id) 

How do I add permissions so that only authenticated user can add,update delete or retrieve objects from the person list in the api. And read-only permissions for non authorized users. I tried going through the docs but it is all very confusing. Can someone explain?

1

1 Answers

1
votes

You need to add IsAuthenticatedOrReadOnly permission class to PersonDetail view.

From the DRF Docs:

The IsAuthenticatedOrReadOnly will allow authenticated users to perform any request. Requests for unauthorised users will only be permitted if the request method is one of the "safe" methods; GET, HEAD or OPTIONS.

from rest_framework.permissions import IsAuthenticatedOrReadOnly


class PersonDetail(generics.RetrieveUpdateDestroyAPIView):
    serializer_class = PersonSerializer
    permission_classes = (IsAuthenticatedOrReadOnly,) # specify the permission class in your view

    def get_object(self):
        person_id = self.kwargs.get('pk',None)
        return Person.objects.get(pk=person_id)