Setting permission policies

We will configure permission policies for the class-based views that work with the Drone model. We will override the value for the permission_classes class attribute for the DroneDetail and DroneList classes.

We will add the same lines of code in the two classes. We will include the IsAuthenticatedOrReadOnly class and our recently declared IsCurrentUserOwnerOrReadOnly permission class in the permission_classes tuple.

Open the restful01/drones/views.py file and add the following lines after the last line that declares the imports, before the declaration of the DroneCategorySerializer class:

from rest_framework import permissions 
from drones import custompermission 

Replace the code that declares the DroneDetail class with the following code in the same views.py file. The new lines are highlighted in the code listing. The code file for the sample is included in the hillar_django_restful_08_01 folder, in the restful01/drones/views.py file:

class DroneDetail(generics.RetrieveUpdateDestroyAPIView): 
    queryset = Drone.objects.all() 
    serializer_class = DroneSerializer 
    name = 'drone-detail' 
    permission_classes = ( 
        permissions.IsAuthenticatedOrReadOnly, 
        custompermission.IsCurrentUserOwnerOrReadOnly, 
        )

Replace the code that declares the DroneList class with the following code in the same views.py file. The new lines are highlighted in the code listing. The code file for the sample is included in the hillar_django_restful_08_01 folder, in the restful01/drones/views.py file:

class DroneList(generics.ListCreateAPIView): 
    queryset = Drone.objects.all() 
    serializer_class = DroneSerializer 
    name = 'drone-list' 
    filter_fields = ( 
        'name',  
        'drone_category',  
        'manufacturing_date',  
        'has_it_competed',  
        ) 
    search_fields = ( 
        '^name', 
        ) 
    ordering_fields = ( 
        'name', 
        'manufacturing_date', 
        ) 
    permission_classes = ( 
        permissions.IsAuthenticatedOrReadOnly, 
        custompermission.IsCurrentUserOwnerOrReadOnly, 
        )
 
    def perform_create(self, serializer): 
        serializer.save(owner=self.request.user) 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.67.251