Django Ajax表单提交错误地重定向到另一个页面 [英] Django Ajax Form submit wrongly redirect to another page

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

问题描述

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

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

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



这是我的update_comment视图:

  def update_comment(request,news_pk):
news = get_object_or_404(News,id = news_pk)
comment_form = CommentForm(request。 POST或无)
如果request.method =='POST'并且comment_form.is_valid():
如果没有request.user.is_authenticated:
返回render(request,'login.html' ,{})
评论= comment_form.cleaned_data.get(评论)
news_comment =新闻评论(user = request.user,评论=评论,新闻=新闻)
news_comment.save( )

#返回重定向(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% },
数据:{'news_pk':{{news.id}},'comments':comments},
异步:true,
beforeSend:function(xhr,settings){
xhr.setRequestHeader( X-CSRFToken, {{csrf_token}});
},
成功:function(data){
if(data.status = ='失败'){
if(data.msg =='用户未登录'){
window.location.href = login;
}其他{
警报(data.msg)
}
}否则if(data.status =='success'){
window.location.reload(); //刷新当前页面。
}

},
});
});

这是我的表格:

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

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

<输入类型= submit value =提交> < / input>

< / form>


解决方案

最后,我做到了!感谢上帝!非常激动!



在先前的代码中,我遇到了三个主要问题。



第一:因为ajax会将news_pk发布到视图 update_comment ,因此我不需要在此视图的url和模板(在< form> 标记的url和

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



第三个问题是我误认为了'comments'和'comment'。'comment'是< textarea> 的name属性,forms.py通过



注释由ajax通过 var注释= $(#js-pl-textarea)。val(),,因此在视图中,我需要使用 comments = request.POST.get( comments,)但不进行注释,这就是为什么'



以下是我的代码。



这里是ajax:

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

$ .ajax({
cache:false,
类型: 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}}));
},
成功:函数(数据){
if(data.status =='失败'){
if(data.msg =='用户未登录') {
window.location.href = login;
} else {
alert(data.msg)
}
} else if(data.status =='success'){
window.location.reload( ); //刷新当前页面。
}

},
});
返回false;

});

这是我的udate_comment视图:

  @login_required 
def update_comment(request):
news_pk = request.POST.get( news_pk,0)
注释= request.POST.get ( comments,)
int(news_pk)> 0和注释:
news_comments = NewsComments()
新闻= News.objects.get(id = int(news_pk))
news_comments.news =新闻
news_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>

<输入类型= submit value =提交> < / input>

< / form>

我非常感谢大家的答复!有了您的答复,我逐步弄清了这些问题!


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.

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

Here is my 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.
                }

                },
        });
    });

Here is my form:

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

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.

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 post But for this part I'm still a some confused,between the button summit way and form submit way.

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

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

Following is my code.

Here is the 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;

    });

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表单提交错误地重定向到另一个页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆