我正在尝试创建一个新的Category
,只需要填充name
字段,但它仍然会显示错误,说明它是必需的。
models.py :
class Category(models.Model):
name = models.CharField(max_length=32, unique=True)
created_at = models.DateTimeField(default=timezone.now)
updated_at = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.name
serializers.py
class CategorySerializer(serializers.Serializer):
id = serializers.IntegerField(required=False)
name = serializers.CharField(max_length=32)
def create(self, validated_data):
return Category.objects.create(**validated_data)
def update(self, instance, validated_data):
pass
views.py
class CategoryList(APIView):
def get(self, request):
"""
Gets all the existing categories
:param request:
:return: Category
"""
categories = Category.objects.all().filter().order_by("name")
serializer = CategorySerializer(categories, many=True)
return Response(serializer.data)
def post(self, request):
"""
Create one new category
:param request:
:return: Category
"""
serializer = CategorySerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=HTTP_201_CREATED)
return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)
引用request.data
向我显示,例如:{'data': {'name': 'Withdrawal'}}
。它显示正在发送和接收的数据,但我不明白为什么会出现这些错误。
答案 0 :(得分:0)
我发现感谢丹尼尔罗斯曼。碰巧我正在使用React和Redux,我的行动如下:
export function createCategory({ data }) {
return {
[CALL_API]: {
endpoint: '/api/categories/',
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({data}),
types: [CREATE_CATEGORY, CREATE_CATEGORY_SUCCESS, CREATE_CATEGORY_FAILURE],
},
}
}
解决方案是删除body
属性中的花括号。