【发布时间】:2020-10-28 18:49:37
【问题描述】:
我有一个模型,它在 models.py 中定义如下
class Comments(models.Model):
Post_Name = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='Comments_Post_Name')
Comment_By = models.ForeignKey(User, on_delete=models.CASCADE, related_name='Comment_By')
Comment = models.CharField(max_length=100000000, blank=True)
def __str__(self):
return self.Post_Name.Post_Caption + " Commented By " + self.Comment_By.username
我想使用 AJAX 更改“评论”,但它没有改变。 我的AJAX视图和Javascript如下。
def EditComment(request):
ctx = {}
if request.method == 'POST':
print(request.POST)
New = Comments.objects.get(id=request.POST['Comment'])
New.Comment = request.POST['Change']
New.save()
print(New.Comment)
ctx = {'result': 'Done'}
return HttpResponse(json.dumps(ctx), content_type='application/json')
这是调用 AJAX 的脚本。
function EditComment() {
var str = document.getElementById('Comment_ID').value
var saveChange = document.getElementById('message-text').innerHTML
console.log(str)
console.log(saveChange)
$.ajax(
{
type: 'POST',
url: "{% url 'EditComment' %}",
data: {
'Comment': str,
'Change': saveChange,
'csrfmiddlewaretoken': '{{ csrf_token }}'
},
dataType: 'json',
success: function (response) {
console.log(response)
},
error: function (rs) {
alert(rs.responseText);
}
}
)
}
另外,在终端窗口中打印了我想要编辑的相同评论对象......只是它的内容没有被编辑......我也在编辑后保存了该对象,但它仍然没有'不保存...
任何解决方案???
【问题讨论】:
标签: python django ajax django-models django-views