403在Django框架中制作ajax Post请求时被禁止的错误 [英] 403 Forbidden error when making an ajax Post request in Django framework

查看:328
本文介绍了403在Django框架中制作ajax Post请求时被禁止的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将jquery集成到我使用Django框架制作的Web应用程序中。然而,我很难试图使一个简单的 ajax 调用工作。我的模板文件包含表单html和javascript来处理ajax调用,如下所示:

 < script type =text /的javascript> 
$(document).ready(function(){
$(#target).submit(function(){
console.log('Form was submitted');
$ .ajax({
type:POST,
url:/ hello /,//或只是url:/ my-url / path /
data: {
query:$(#query).val()
},
success:function(data){
console.log(data);
}
});
return false;
});
})
< / script>
< form id =targetaction =。 method =post> {%csrf_token%}
< input id =querytype =textvalue =Hello there>
< input type =submitvalue =搜索最近的推文>
< / form>

我的 views.py 处理ajax调用看起来像:

 从django.core.context_processors导入csrf 
从django.shortcuts import render_to_response $来自django.template.loader的
从django.template导入get_template
导入Context,RequestContext
from django.views.decorators.csrf import ensure_csrf_cookie
from django.http import HttpResponse

#访问资源
def hello(request):
c = {}
c.update(csrf(request))
如果request.is_ajax():
t = get_template('template.html')
#html = t.render(Context({'result':'hello world'}))
con = RequestContext(request,{'result ':'hello world'})
return render_to_response('template.html',c,con)
else:
return HttpResponse('Not working!')

我试图跟随官方跨站点请求伪造保护的文档并查看了几个解决类似问题的stackoverflow问题。我在 html 模板文件中包含了 {%csrf_token%} ,但仍然似乎没有工作。我在控制台中收到一个错误提示ajax调用失败:

  POST http://127.0.0.1:8000/hello / 403(FORBIDDEN)

如何传递结果变量以及我的http响应,并获得ajax调用工作顺利?任何帮助深深感激。



编辑1



我没有据推测,与我的发布请求一起传递 csrf 令牌。根据文档,我将以下代码添加到我的模板javascript:

  function getCookie(name){
var cookieValue = null;
if(document.cookie&& document.cookie!=''){
var cookies = document.cookie.split(';');
for(var i = 0; i< cookies.length; i ++){
var cookie = jQuery.trim(cookies [i]);
//这个cookie字符串是否以我们想要的名字开头?
if(cookie.substring(0,name.length + 1)==(name +'=')){
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
console.log(csrftoken);

// Ajax调用
函数csrfSafeMethod(method){
//这些HTTP方法不需要CSRF保护
return(/ ^(GET | HEAD | OPTIONS 。| TRACE)$ /试验(方法));
}
$ .ajaxSetup({
crossDomain:false,//避免需要相同的测试
beforeSend:function(xhr,settings){
if(!csrfSafeMethod (settings.type)){
xhr.setRequestHeader(X-CSRFToken,csrftoken);
}
}
});

当我在浏览器中刷新模板html页面时,我得到 null ,表明cookie未设置或未定义。我缺少什么?

解决方案

因为你没有发布 csrfmiddlewaretoken ,所以Django禁止你。
此文档可以帮助您。 p>

I am trying to integrate jquery into a web application I am making with Django framework. I am however having a hard time trying to make a simple ajax call to work. My template file that contains the form html and javascript to handle the ajax call looks like:

<script type="text/javascript">
$(document).ready(function() {
$( "#target" ).submit(function() {
console.log('Form was submitted');
$.ajax({
        type: "POST",
        url: "/hello/",  // or just url: "/my-url/path/"
        data: {
            query: $( "#query" ).val()   
        },
        success: function(data) {
            console.log(data);
        }
    });
return false;
  });   
  })
</script>
<form id="target" action="." method="post">{% csrf_token %}
 <input id= "query" type="text" value="Hello there">
 <input type="submit" value="Search Recent Tweets">
</form>

My views.py that is supposed to handle the ajax call looks like:

 from django.core.context_processors import csrf
 from django.shortcuts import render_to_response
 from django.template.loader import get_template
 from django.template import Context,RequestContext
 from django.views.decorators.csrf import ensure_csrf_cookie
 from django.http import HttpResponse

 # access resource
 def hello(request):
  c = {}
  c.update(csrf(request))
  if request.is_ajax():
        t = get_template('template.html')
        #html = t.render(Context({'result': 'hello world'}))
        con = RequestContext(request, {'result': 'hello world'})
        return render_to_response('template.html', c, con)
  else:
        return HttpResponse('Not working!') 

I have tried to follow the official documentation on Cross-Site Request Forgery Protection and also looked at several stackoverflow questions addressing a similar problem. I have included the {% csrf_token %} in my html template file but it still doesn't seem to be working. I get an error in the console suggesting that the ajax call failed:

POST http://127.0.0.1:8000/hello/ 403 (FORBIDDEN)   

How do I pass the result variable along with my http response and get the ajax call to work smoothly? Any help is deeply appreciated.

Edit-1

I wasn't supposedly passing the csrf token along with my post request. SO as per the documentation I added the following code to my template javascript:

function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
    var cookies = document.cookie.split(';');
    for (var i = 0; i < cookies.length; i++) {
        var cookie = jQuery.trim(cookies[i]);
        // Does this cookie string begin with the name we want?
        if (cookie.substring(0, name.length + 1) == (name + '=')) {
            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
            break;
        }
    }
}
    return cookieValue;
}
var csrftoken = getCookie('csrftoken');
console.log(csrftoken);

//Ajax call
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    crossDomain: false, // obviates need for sameOrigin test
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type)) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});

When I refresh the template html page in the browser, I get null in the console, suggesting that the cookie is not set or not defined. What am I missing?

解决方案

Because you did not post the csrfmiddlewaretoken, so Django forbid you. this document can help you.

这篇关于403在Django框架中制作ajax Post请求时被禁止的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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