简体   繁体   中英

Django-rest-framework How to add additional data to request.data

I am using DRF & token authentication system to deal with the API. Whenever I send the data from the client it sends two of three required fields: title and name . But created_by is given by request.user in the backend.

So I need the following, that of course does not work as expected:

class DefaultViewSet(viewsets.ModelViewSet):
    """
    API endpoint
    """
    queryset = Default.objects.all().order_by('-updated_at')
    serializer_class = DefaultSerializer
    permission_classes = [permissions.IsAuthenticated]
    filterset_fields = ['created_by', 'title', 'name']

    def create(self, request, *args, **kwargs):
        request.data['created_by'] = request.user.id
        super().create(request, *args, **kwargs)

Since I can't change request.data object I should completely override create method. Therefore there is no easy way to do the previous stuff, right? or there is?

You should override perform_create method which calls the save method of the serializer and send additional keyword arguments as the docs says:

def perform_create(self, serializer):
    request = serializer.context['request']
    serializer.save(created_by=request.user.id)

The original method does:

def perform_create(self, serializer):
    serializer.save()

I just managed to handle it in the create() function by using this example in the documentation:

    def create(self, request, *args, **kwargs):
        serializer = DefaultSerializer(data=request.data, context={'request': request})
        if not serializer.is_valid():
            return Response(serializer.errors, status=400)
        serializer.save(created_by=request.user)
        return Response({
            'data': serializer.data
        })

I think add it to your serializer class is better

created_by = serializers.HiddenField(default=serializers.CurrentUserDefault())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM