我有一个REST端点。当我通过DRF GUI访问此端点时,可以手动输入数据,它可以成功运行。我的模型如下:
class Post(models.Model):
title = models.CharField(max_length=100, null=False)
content = HTMLField()
created_at = models.DateField(auto_now_add=True)
authors = models.ManyToManyField(User)
我的序列化器和视图如下:
class CreatePostSerializer(CreateAPIView):
serializer_class = PostSerializer
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = ('title', 'content', 'authors')
当我实际上尝试通过Ajax将数据提交到端点时,就像这样:
$.ajax({
type: 'POST',
url: '/api/save-post/',
data: {
"csrfmiddlewaretoken": getCookie('csrftoken'),
"title": "dasf",
"desct": "dasf",
"content": "fdasf",
"authors": [1,2]
},
success: function (msg) {
console.log(msg);
}
});
我收到一条错误消息:{"authors":["This list may not be empty."]}
,并发送了有效载荷:
title: dasf
desct: dasf
content: fdasf
authors[]: 1
我尝试将contentType更改为application / json,我尝试了几乎所有方法,但似乎没有任何效果。我该如何做才能使我的端点理解我要发送的内容?
答案 0 :(得分:0)
var authors = [];
authors[0] = 1;
authors[1] = 2;
var arr = {
"csrfmiddlewaretoken": getCookie('csrftoken'),
"title": "dasf",
"desct": "dasf",
"content": "fdasf",
"authors": authors
};
$.ajax({
url: '/api/save-post/',
type: 'POST',
data: arr,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(msg) {
alert(msg);
}
});