表单提交错误地重定向到另一个页面

表单提交错误地重定向到另一个页面

本文介绍了Django Ajax 表单提交错误地重定向到另一个页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When I use ajax to submit a comment form in Django,the page will redirect to a blank page shows me the success data:

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

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

,but not stay in current page.I want the page stay in current page and show me the new comment.

这是我的 update_comment 视图:

Here is my update_comment view:

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>

推荐答案

我终于成功了!感谢主!非常激动!

Finally I made it!Thanks Lord!Very excited!

我之前的代码有三个主要问题.

I have Three major issues in my previous code.

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

First:Since the ajax will post the news_pk to the view update_comment,so I don't need add news_pk in this view's url and template(in the url of <form> tag and the url in the ajax),so I removed them,or the data will still pass through Form but not ajax.

第二:我的绑定不正确,我在表单上有点击处理程序,它应该是提交处理程序.如果我将它绑定到一个按钮,那么我会使用单击处理程序.Ajax 在 Django 帖子中不起作用但是这部分我还是有点迷茫,按钮顶的方式和表单提交的方式.

Second:My binding is incorrect,I have the click handler on the form it should be a submit handler. If I was binding it to a button then I'd use click a handler.Ajax not work in Django postBut for this part I'm still a some confused,between the button summit way and form submit way.

第三个问题是我把'comments'和'comment'弄错了.'comment'是的name属性,forms.py通过它获取数据.

The third issue is I mistaked 'comments' and 'comment'.'comment' is the name attribute of <textarea> ,through which forms.py gets the data.

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

comments is defined by ajax through var comments = $("#js-pl-textarea").val(), so in the view I need use comments = request.POST.get("comments", "") but not comment,that's the reason why 'post failed'.

以下是我的代码.

这里是ajax:

 $("#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 视图:

Here is my udate_comment view:

@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')

这是我在模板中的表单:

Here is my form in template:

<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>

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

I really appreciate everyone's reply!With your reply I figured out these issue step by step!

这篇关于Django Ajax 表单提交错误地重定向到另一个页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 22:26