Reputation: 3474
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?
Upvotes: 0
Views: 2878
Reputation: 11
I think add it to your serializer class is better
created_by = serializers.HiddenField(default=serializers.CurrentUserDefault())
Upvotes: 1
Reputation: 3474
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
})
Upvotes: 0
Reputation: 780
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()
Upvotes: 2