我正在使用Django Rest Framework执行API项目。
我有以下方式定义的Django模型:
class Profile(CreatedUpdatedModel, models.Model):
owner = models.ForeignKey(Owner, models.CASCADE)
start_date = models.DateField(gettext_lazy("Start"), help_text=gettext_lazy("YYYY-MM-DD format"))
end_date = models.DateField(gettext_lazy("End"), help_text=gettext_lazy("YYYY-MM-DD format"))
category = models.ManyToManyField(OwnerCategory)
tags = models.ManyToManyField(OwnerTag)
我从网页执行POST API调用,该调用传递了如下所示的JSON数据:
{start_date: '2019-11-20' , end_date: '2019-11-21', owner: '65', category: '[20, 21, 22]', tags: '[]' }
我想用我通过JSON传递的参数将模型保存在数据库中
这是我在views.py中的REST视图:
@permission_required()
class ProfileViewSet(ViewSet):
@action(detail=False, methods=['post'])
def new_profile(self, request, pk=None):
serializer = serializers.ProfileSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
这是我在serializers.py中的REST序列化器
class ProfileSerializer(ModelSerializer):
class Meta:
model = Profile
fields = ('owner', 'start_date', 'end_date', 'category', 'tags', )
问题在于语句serializer.is_valid()
是False
。
这段代码我错在哪里?
有人可以帮助我吗?
----- 编辑 ----
我看着serializer.errors
,这是输出:
{'owner': [ErrorDetail(string='This field is required.', code='required')], 'category': [ErrorDetail(string='Expected a list of items but got type "str".', code='not_a_list')], 'tags': [ErrorDetail(string='This field is required.', code='required')]}
我还查看了request.data
,我发现字典包含了我通过API传递的所有数据
答案 0 :(得分:0)
您要发送的内容不是有效的json数据。这是您在json中的外观:
{
"start_date": "2019-11-20",
"end_date": "2019-11-21",
"owner": 65,
"category": [
20,
21,
22
],
"tags": []
}