Saving information about users that make requests

Whenever a user performs an HTTP POST request to the drone resource collection to create a new drone resource, we want to make the authenticated user that makes the request the owner of the new drone. In order to make this happen, we will override the perform_create method in the DroneList class declared in the views.py file.

Open the restful01/drones/views.py file and replace the code that declares the DroneList class with the following code. 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', 
        ) 
 
    def perform_create(self, serializer): 
        serializer.save(owner=self.request.user) 

The generics.ListCreateAPIView class inherits from the CreateModelMixin class and other classes. The DroneList class inherits the perform_create method from the rest_framework.mixins.CreateModelMixin class.

The code that overrides the perform_create method provides an additional owner field to the create method by setting a value for the owner argument in the call to the serializer.save method. The code sets the owner argument to the value of self.request.user, that is, to the authenticated user that is making the request. This way, whenever a new Drone is created and persisted, it will save the User associated to the request as its owner.

..................Content has been hidden....................

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