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.
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.
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".
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With