gpt4 book ai didi

python - 发布到 Django 休息框架

转载 作者:太空狗 更新时间:2023-10-30 00:24:49 25 4
gpt4 key购买 nike

我想使用 post 发布到我的 Django 服务器,这样我就可以添加一个 todo 项目。这是模型:

class Todo(models.Model):
title = models.CharField(max_length=200);
text = models.TextField()
completed = models.BooleanField(default=False)
created_at = models.DateTimeField(default=datetime.now, blank = True )
def __str__(self):
return self.title

和序列化器:

class TodoSerializer(serializers.ModelSerializer):
class Meta:
model = Todo
fields = ("id", 'title','text', 'completed', 'created_at')

并查看:

class TodoList(APIView):
def get(self,request):
todo=Todo.objects.all()
serializer=TodoSerializer(todo,many=True)
return Response(serializer.data)
def post(self,request):
Todo.objects.create(
title=request.POST.get('title'),
text=request.POST.get('text'))
return HttpResponse(status=201)

我的发帖请求是

{ "title": "new title",
"text": "a test text"}

它告诉我

IntegrityError at /todos/
(1048, "Column 'title' cannot be null")

作为Django的新手,我不明白这个错误。有什么想法吗?

最佳答案

您需要访问request.data 而不是request.POST,

def post(self,request):
serializer = TodoSerializer(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)

关于python - 发布到 Django 休息框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45205039/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com