首页 > 解决方案 > Django Ajax 表单提交错误地重定向到另一个页面

问题描述

当我在 Django 中使用 ajax 提交评论表单时,页面将重定向到一个空白页面,显示成功数据:

{"status":"success", "msg":"添加成功"}

,但不停留在当前页面。我希望页面停留在当前页面并向我显示新评论。

这是我的 update_comment 视图:

def update_comment(request, news_pk):
    news = get_object_or_404(News, id=news_pk)
    comment_form = CommentForm(request.POST or None)
    if request.method == 'POST' and comment_form.is_valid():
        if not request.user.is_authenticated:
            return render(request, 'login.html', {})
        comments = comment_form.cleaned_data.get("comment")
        news_comment = NewsComments(user=request.user, comments=comments, news=news)
        news_comment.save()

    # return redirect(reverse('news:news_detail', kwargs={'news_pk': news.id}))
        return HttpResponse('{"status":"success", "msg":"添加成功"}', content_type='application/json')
    else:
        return HttpResponse('{"status":"fail", "msg":"添加失败"}', content_type='application/json')

这是我的ajax:

$(document).on('submit', 'comment_form', function(e){
        e.preventDefault();

        $.ajax({
            cache: false,
            type: "POST",
            url:"{% url 'operation:update_comment' news.id %}",
            data:{'news_pk':{{ news.id }}, 'comments':comments},
            async: true,
            beforeSend:function(xhr, settings){
                xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
            },
            success: function(data) {
                if(data.status == 'fail'){
                    if(data.msg == '用户未登录'){
                        window.location.href="login";
                    }else{
                        alert(data.msg)
                    }
                }else if(data.status == 'success'){
                    window.location.reload();//refresh current page.
                }

                },
        });
    });

这是我的表格:

<form id="comment_form" action="{%  url 'operation:update_comment' news.id %}" method="POST" >
{% csrf_token %}

<textarea id="comment_textarea"name="comment"></textarea>

<input type="submit" value="Submit"> </input>

</form>

标签: ajaxdjango-formsdjango-templatesdjango-views

解决方案


终于我成功了!感谢上帝!非常兴奋!

我以前的代码中有三个主要问题。

第一:由于ajax会将news_pk发布到视图update_comment,所以我不需要在这个视图的url和模板中添加news_pk(在<form>标签的url和ajax中的url中),所以我删除了它们,或者数据仍然会通过 Form 但不会通过 ajax。

第二:我的绑定不正确,我在表单上有点击处理程序,它应该是一个提交处理程序。如果我将它绑定到一个按钮,那么我会使用单击处理程序。Ajax 在 Django 帖子中不起作用 但是对于这一部分,我仍然有些困惑,在按钮峰会方式和表单提交方式之间。

第三个问题是我弄错了'comments'和'comment'。'comment'是<textarea>forms.py获取数据的name属性。

评论是由ajax定义的, var comments = $("#js-pl-textarea").val(),所以在我需要使用comments = request.POST.get("comments", "")但不需要评论的视图中,这就是“发布失败”的原因。

以下是我的代码。

这是阿贾克斯:

 $("#comment_form").submit(function(){
        var comments = $("#js-pl-textarea").val()

        $.ajax({
            cache: false,
            type: "POST",
            url:"{% url 'operation:update_comment' %}",
            data:{'news_pk':{{ news.pk }}, 'comments':comments},
            async: true,
            beforeSend:function(xhr, settings){
                xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
            },
            success: function(data) {
                if(data.status == 'fail'){
                    if(data.msg == '用户未登录'){
                        window.location.href="login";
                    }else{
                        alert(data.msg)
                    }
                }else if(data.status == 'success'){
                    window.location.reload();//refresh current page.
                }

                },
        });
        return false;

    });

这是我的 udate_comment 视图:

@login_required
def update_comment(request):
        news_pk = request.POST.get("news_pk", 0)
        comments = request.POST.get("comments", "")
        if int(news_pk) > 0 and comments:
            news_comments = NewsComments()
            news = News.objects.get(id=int(news_pk))
            news_comments.news = news
            news_comments.comments = comments
            news_comments.user = request.user
            news_comments.save()
            return HttpResponse('{"status":"success", "msg":"添加成功"}', content_type='application/json')
        else:
            return HttpResponse('{"status":"fail", "msg":"添加失败"}', content_type='application/json')

这是我在模板中的表格:

<form id="comment_form" action="{%  url 'operation:update_comment'%}" method="POST" >
{% csrf_token %}

<textarea id="js-pl-textarea"name="comment"></textarea>

<input type="submit" value="Submit"> </input>

</form>

非常感谢大家的回复!有了你们的回复,我一步步解决了这些问题!


推荐阅读