Python Django RestFramework route trigger
Question: I'am building an API using python 2.7 and django 1.7 and I'm facing a problem.
I'm not an expert in Rest Framework but I understand the basic mechanisms.

I can resume my problem by giving you an example. I have a route lets say

    
    
    /api/project/
    

Django Rest Framework provides me all basic operations for this route and I
don't need to write them e.g:

    
    
    POST, GET, PUT, DELETE => /api/project/
    

The fact is, I want to do some operation when I create a new project. I want
to add the id of the user who has created the new project.

I want to add some kind of trigger/callback to the create function:

    
    
    class ProjectViewSet(viewsets.ModelViewSet):
        queryset = Project.objects.all()
        serializer_class = ProjectSerializer
    
        def create(self, request, *args, **kwargs):
    

I want to keep the internal behavior of Rest Framework (I don't want to
rewrite the route functions), but I want the route to do extra stuff and I
need the request object in my trigger/callback. Something like

    
    
    def callback(request, instance):
        instance.created_by = request.user
        instance.save()
    

Do you have any ideas?

Thank you.


Answer: You need to add creator_id field to your serializer as well as to model
represented by the resource. Then you can do something like this in your
view:-

    
    
    import copy
    
    class ProjectViewSet(viewsets.ModelViewSet):
    
          ...
    
          def create(self, request, *args, **kwargs):
              data = copy.deepcopy(request.data)
              data['creator_id'] = request.user.id
              request._data = data
    
              return super(ProjectViewSet, self).create(request, *args, **kwargs)
    

