[英]Serializer.is_valid() is always False
I have the following Serializer
to handle a user: 我有以下
Serializer
来处理用户:
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: 目前,基于Django REST教程,我处理POST请求以注册新用户的视图是:
@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: 因此,为了模拟具有POST请求的客户端,我使用以下几行:
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, 但是,尽管
print(data)
按预期进行检索,
{"login": "mylogin", "mail": "mymail", "password": "mypassword"}
The serializer.is_valid()
always returns False
. serializer.is_valid()
始终返回False
。
Am I missing any processing of my request? 我是否缺少对请求的任何处理?
EDIT: 编辑:
I got the following info with serializer.errors
: 我通过
serializer.errors
得到了以下信息:
{'non_field_errors': ['Invalid data. Expected a dictionary, but got str.']}
You dont have to convert a dictionary to string when using requests
library's json
option. 使用
requests
库的json
选项时,您不必将字典转换为字符串。 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)
The solution is to use ast.literal_eval(request.data)
to convert the string to a dictionary. 解决方案是使用
ast.literal_eval(request.data)
将字符串转换为字典。 I use request.data
instead of manually parsing request.body
. 我使用
request.data
而不是手动解析request.body
。
However, v1k45's answer is the best solution, as I do not need to convert my dict to a string before sending my request. 但是,v1k45的答案是最好的解决方案,因为在发送请求之前,我不需要将dict转换为字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.