[Fixed]-How to pass a extra parameter using perform_create of django rest framwork?

1👍

you should add a perform_create() to your PostViewSet specifying the name of the field which has to be filled out on save:

class PostViewSet(viewsets.ModelViewSet):

    permission_classes = (IsOwnerOrReadOnly,)
    queryset = PostModel.objects.all()
    serializer_class = PostSerializer

    def perform_create(self, serializer):
        serializer.save(author = self.request.user)

remember your Post model should have an author field

👤montxe

0👍

Depending on what you want to do, you should:

  • Mark the author field as either read_only=True or required=False
  • Set the author field with CreateOnlyDefault

For example:

class PostSerializer(serializers.ModelSerializer):
    spoter = serializers.PrimaryKeyRelatedField(
        queryset= User.objects.all(),
    )

    class Meta:
        model = PostModel
        fields = ('author','text')
        extra_kwargs = {
            'author': {
                'read_only': True,
                'default': serializers.CurrentUserDefault(),
            }
        }

0👍

Just exclude the author field from your serializer fields. When calling serializer.save you can pass any field, not necessarily the fields of the serializer.

Serializer fields are those included in the request.data and author is not such a field.

Leave a comment