【问题标题】:Ajax POST request 200 but Form is not validAjax POST 请求 200 但表单无效
【发布时间】: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


【解决方案1】:

它返回 200,因为你说返回 200。确实,你返回:

return render(request, 'blog/post.html', context)

render 将呈现模板并将其包装为 HttpResponse,默认情况下为 status = 200

因此,您应该返回不同的内容,例如 JsonResponsestatus=400

from django.http import JsonResponse

def view_post(request, slug):
    post = Post.objects.get(slug=slug)
    comments = post.comments.filter(
        approved_comment=True, reply=None
    ).order_by('-date_posted')
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            form.instance.author = request.user
            form.instance.post = post
            form.instance.reply_id = request.POST.get('comment_id')
            form.save()
        else:
            return JsonResponse({'status': 'fail'}, status=400)
    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)

【讨论】:

  • 你是绝对正确的,但是我该如何解决这个问题?表格本身有问题吗?
  • @Adrian0012:您可以在(第一个)else 子句中使用print(form.errors),以显示表单的错误。
猜你喜欢
  • 2017-09-14
  • 2019-07-19
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
  • 2018-08-03
  • 2020-12-15
  • 1970-01-01
  • 2019-08-26
相关资源
最近更新 更多