【发布时间】:2020-10-16 12:08:41
【问题描述】:
我有一个引用其他模型的模型,我正在尝试使用 ajax 保存数据
例子:
class Friend(models.Model):
name = ...
class Main(models.Model):
name = ....
friend = models.ForeignKey(Friend, on_delete=models.CASCADE)
所有正文都来自 ajax(fetch) 请求
我有一个表格 (html),并将数据添加到单元格,然后使用 输入事件,发送数据。
像这样:
input.addEventListener("keyup", function (e) {
//in this scenario I already have the whole row
// get full_row `row_data`
post_ajax = {
method: "POST",
headers: {
"X-CSRFToken": crf_token, // I get it with a regular expression
"Content-Type": "application/json",
"X-Requested-With": "XMLHttpRequest",
Accept: "application/json",
},
body: JSON.stringify(row_data),
};
fetch("my_url", post_ajax)
.then((res) => res.json())
.catch((error) => console.error("Error:", error))
.then((response) => console.log("Success:", response));
});
我的视图功能
def save_post(request):
if request.is_ajax and request.method == "POST":
body_unicode = request.body.decode('utf-8')
data = json.loads(body_unicode)
print('here the data arrives',data)
# here the data arrives {'name': 'Ale', 'friend_id': 22}
Main.objects.create(name=data['name'], friends=data['friend_id'])
return JsonResponse({"instance": data}, status=200)
return JsonResponse({"error": ""}, status=400)
这是错误
raise TypeError("%s() got an unexpected keyword argument '%s'" %
(cls.__name__, kwarg))
TypeError: Main() got an unexpected keyword argument 'Friends'
有什么想法或建议吗?
【问题讨论】:
-
请提供您用于向 Django 视图发送 AJAX 请求的模板代码
-
@MichaelHawkins 我更新了我的问题
-
打印出来的 JSON 数据是什么样的?
-
@MichaelHawkins like this
{'name': 'Ale', 'friend_id': 22...}is js and python json.loads -
我在下面编辑了我的答案 - 看看是否有效
标签: python django ajax django-models