【发布时间】:2020-09-23 23:25:48
【问题描述】:
我正在努力通过 Ajax 添加 cmets 和回复,POST.request 可以,但是表单本身无效,因此没有数据保存在数据库中。请看下面我的一些代码: 观看次数
def view_post(request, slug):
post = Post.objects.get(slug=slug)
comments = post.comments.filter(approved_comment=True, reply=None).order_by('-date_posted')
form = CommentForm()
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
reply_id = request.POST.get('comment_id')
data = None
if reply_id:
data = Comment.objects.get(id=reply_id)
comment.author = request.user
comment.post = post
comment.reply = data
comment.save()
else:
print('form not valid')
else:
form = CommentForm()
context = {
'post' : post,
'comments' : comments,
'form' : form
}
if request.is_ajax():
html = render_to_string('blog/comments.html', context, request=request)
return JsonResponse({ 'form' : html })
return render(request, 'blog/post.html', context)
这里是 Ajax 请求
$.ajax({
method: 'POST',
url: `/post/${slug}/`,
data: $(this).serialize(),
dataType: 'json',
success: function(response) {
$(event.target).parents('.reply-form').hide()
$('main-comment-section').html(response['form']);
$('textarea').val('');
},
error: function(rs, e) {
console.log(rs.responseText);
},
})
event.preventDefault();
})
我将不胜感激任何指导。谢谢!
-更新-
非常感谢您的帮助,通过打印 form.errors 它帮助我了解了问题所在。它与模型中的关系和必填字段有关。
【问题讨论】:
-
你在哪里指定返回不同的东西?
-
@WillemVanOnsem 很抱歉,但我不太明白你想说什么。你能说得更清楚一点吗?
标签: django ajax django-forms