我使用的是djangorestframework==3.12.2。我有这个序列化程序。有些领域,如“描述英语”我不想被要求。。。
class ValidateNewCoopSerializer(serializers.Serializer):
coop_name=serializers.CharField()
street=serializers.CharField()
address_public=serializers.CharField()
city=serializers.CharField()
state=serializers.CharField()
zip=serializers.CharField()
county=serializers.CharField()
country=serializers.CharField()
websites=serializers.CharField()
contact_name=serializers.CharField()
contact_name_public=serializers.CharField()
contact_email=serializers.CharField()
contact_email_public=serializers.CharField()
contact_phone=serializers.CharField()
contact_phone_public=serializers.CharField()
scope=serializers.CharField()
tags=serializers.CharField(required=False)
desc_english=serializers.CharField(required=False)
desc_other=serializers.CharField(required=False)
req_reason=serializers.CharField()
@api_view(('POST',))
def save_to_sheet_from_form(request):
"""
This is supposed to write to a Google sheet given a form coming from
the client.
"""
valid_ser = ValidateNewCoopSerializer(data=request.data)
if valid_ser.is_valid():
post_data = valid_ser.validated_data
...
return Response(post_data, status=status.HTTP_201_CREATED)
else:
return Response(valid_ser.errors, status=status.HTTP_400_BAD_REQUEST)
不过,我注意到,当我提交请求时,字段被标记为not required,并且返回时出现错误。。。
curl 'http://localhost:8000/save_to_sheet_from_form/' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:88.0) Gecko/20100101 Firefox/88.0' -H 'Accept: */*' -H 'Accept-Language: en-US,en;q=0.5' --compressed -H 'Referer: http://localhost:3001/' -H 'Content-Type: application/json' -H 'Origin: http://localhost:3001' -H 'Connection: keep-alive' -H 'Pragma: no-cache' -H 'Cache-Control: no-cache' --data-raw '{"coop_name":"","street":"","address_public":"no","city":"","state":"IL","zip":"","county":"","country":"US","websites":"","contact_name":"","contact_name_public":"no","contact_email":"","contact_email_public":"no","contact_phone":"","contact_phone_public":"no","scope":"local","tags":"","desc_english":"","desc_other":"","req_reason":"add"}'
结果
{"coop_name":["This field may not be blank."],"street":["This field may not be blank."],"city":["This field may not be blank."],"zip":["This field may not be blank."],"county":["This field may not be blank."],"websites":["This field may not be blank."],"contact_name":["This field may not be blank."],"contact_email":["This field may not be blank."],"contact_phone":["This field may not be blank."],"tags":["This field may not be blank."],"desc_english":["This field may not be blank."],"desc_other":["This field may not be blank."]}
如何配置序列化程序,使这些字段实际上不是必需的?