Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializer validated_data is empty even when is_valid is True

Following code returning an empty json.

def create_account(request):
    serializer = UserSerializer(data={'name': request.GET.get('name'), 'surname': request.GET.get('surname'),
                                      'password': request.GET.get('password'), 'email': request.GET.get('email')})
    if not serializer.is_valid():
        return HttpResponse(status=401,content=serializer.errors)

    serializer.save()
    return Response(serializer.data)

And this is my serializer

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('name', 'surname', 'password', 'email')

    def create(self, validated_data):
        return User.objects.create(**validated_data)

When i send a request, serializer.initial_data is filled correctly. is_valid is returning True but validated_data is empty.

like image 737
Sefa Avatar asked Sep 24 '15 13:09

Sefa


People also ask

What does serializer Is_valid do?

is_valid perform validation of input data and confirm that this data contain all required fields and all fields have correct types. If validation process succeded is_valid set validated_data dictionary which is used for creation or updating data in DB.

How do I know if my serializer is valid?

We can validate the serializer by calling the method " is_valid() ". It will return the boolean(True/False) value. If the serializer is not valid then we can get errors by using the attribute "errors".

What is many true in serializer Django?

by setting many=True you tell drf that queryset contains mutiple items (a list of items) so drf needs to serialize each item with serializer class (and serializer.data will be a list) if you don't set this argument it means queryset is a single instance and serializer.data will be a single object)


1 Answers

It doesn't look like you're using a custom User model and django.contrib.auth.models.User doesn't have the name and surname fields. It does however have first_name and last_name. Try using those as fields in your serializer instead since they are model fields. Otherwise you'll have to override to_internal_value as this answer suggests.

Unable to get a non-model field in the validated_data of a Django Rest Framework serializer

like image 151
jstewart379 Avatar answered Sep 20 '22 08:09

jstewart379