Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework serializer create() doesn't get triggered

I have the following serializer

class MyModelSerializer(serializers.ModelSerializer):
    user = UserSerializer()

    def create(self, validated_data):
        print("TEST")
        MyModel, created = MyModel.objects.get_or_create(**validated_data)
        return MyModel

    class Meta:
        model = MyModel
        fields = ('pk', 'title', 'user', 'movie', 'timestamp', 'text',)

and the following viewset:

class MyModelViewSet(viewsets.ModelViewSet):
    queryset = MyModel.objects.all()
    serializer_class = MyModelSerializer

When I make an POST request to the endpoint corresponding to specified viewset, the create() method does absolutely nothing. I tried to print out in console TEST as you can see, but nothing.

Does anyone have an idea about this strange behavior?

Thanks in advace!

Edit: API call:

return axios({
  method: 'post',
  url: 'http://localhost:8000/api/mymodel/',
  data: {
     title: this.title,
     movie: this.id,
     text: this.text,
     user: this.user
}
like image 337
yierstem Avatar asked Sep 26 '18 17:09

yierstem


Video Answer


1 Answers

If you look at the implementation of POST handling in a ViewSet, you can find this:

def create(self, request, *args, **kwargs):
    serializer = self.get_serializer(data=request.data)
    serializer.is_valid(raise_exception=True)
    self.perform_create(serializer)
    headers = self.get_success_headers(serializer.data)
    return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

Your create method is called after serializer validates the data.

The error you see (user already exists) is a result of calling serializer.is_valid from the snippet above.

Therefore, it never gets to call your create. Your create would be called as part of self.perform_create() from this snippet above.

So this means that you are trying to create a user which already exists. So in your model you have unique username.

like image 85
Enthusiast Martin Avatar answered Oct 09 '22 10:10

Enthusiast Martin