Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass user id into a serializer with request data?

I have a project that autenticate by oauth2_provider.ext.rest_framework.OAuth2Authentication. There is a token in the request headers for authenticating and identifying. I think I should not include user id in the request data explicitly when process a create action. But serializer need user info to create a new instance. So I include a user_id field in serializer, and put the value into the request.data dict after authenticating.

Is it good? Is there any better way?

serializers.py

class serializer(serializers.Serializer):
    user = UserSerializer(read_only=True)
    user_id = serializers.UUIDField(write_only=True)
    content = serializers.CharField()

views.py

class CommentList(generics.ListCreateAPIView):
    def create(self, request, *args, **kwargs):
        request.data['user_id'] = request.user.id
        return super(CommentList, self).create(request)
like image 491
Xiao Avatar asked Feb 05 '23 20:02

Xiao


1 Answers

It is cleaner to override create(validated_data) in your serializer:

class CommentSerializer(serializers.Serializer):
    ...

    def create(self, validated_data):
      user = self.context['request'].user
      comment = Comment.objects.create(
         user=user, 
         **validated_data
      )
      return comment

See http://www.django-rest-framework.org/api-guide/serializers/#saving-instances

Then you do not need to customise your view, you can just use a generic view.

like image 187
pchiquet Avatar answered Mar 29 '23 17:03

pchiquet