floflo29 floflo29 - 26 days ago 5
JSON Question

Serializer.is_valid() is always False

I have the following

Serializer
to handle a user:

class FriendSerializer(serializers.Serializer):

login = serializers.CharField(max_length=15, required=True)
password = serializers.CharField(max_length=15, required=True)
mail = serializers.CharField(max_length=50, required=True)


Currently, my view which processes the POST request to register a new user is, based on the Django REST tutorial:

@api_view(['POST'])
def register_new_user(request):

if request.method == 'POST':
print('POST request !')

stream = BytesIO(request.body)
data = JSONParser().parse(stream)

print(data)

serializer = FriendSerializer(data=data)

print(serializer.is_valid())

else:
print('Not a POST request!')

return HttpResponse('Nothing')


Thus, to simulate a client with a POST request, I use the following lines:

import requests
import json

json_data = json.dumps({'login': 'mylogin', 'password': 'mypassword', 'mail': 'mymail'})
r = requests.post('http://127.0.0.1:8000/register_new_user', json=json_data)


However, although the
print(data)
retrieves, as expected,

{"login": "mylogin", "mail": "mymail", "password": "mypassword"}


The
serializer.is_valid()
always returns
False
.

Am I missing any processing of my request?

EDIT:

I got the following info with
serializer.errors
:

{'non_field_errors': ['Invalid data. Expected a dictionary, but got str.']}

Answer

You dont have to convert a dictionary to string when using requests library's json option. This should work:

import requests

data = {'login': 'mylogin', 'password': 'mypassword', 'mail': 'mymail'}
r = requests.post('http://127.0.0.1:8000/register_new_user', json=data)