就在中Django框架AJAX Post请求时,403 Forbidden错误 [英] 403 Forbidden error when making an ajax Post request in Django framework

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

问题描述

我想jQuery的集成到Web应用程序我正在与Django框架。不过,我有一个很难试图做一个简单的 AJAX 调用工作。包含表单的HTML和JavaScript来处理Ajax调用我的模板文件是这样的:

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>

我的 views.py 是应该来处理Ajax调用如下:

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

我试图遵循跨站请求伪造官方文件保护也看了几个计算器的问题解决了类似的问题。我已经包括 {%csrf_token%} 在我的 HTML 模板文件,但它似乎仍不奏效。我得到一个错误在控制台提示AJAX调用失败:

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)   

我如何通过结果变量与我的HTTP响应,并得到Ajax调用工作的顺利开展?任何帮助表示深深的AP preciated。

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.

修改-1

我是不是理应传递 CSRF 与我的职务请求令牌沿。这样每个文件添加以下code,以我的模板的javascript:

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);
        }
    }
});

在我刷新模板HTML页面在浏览器中,我得到在控制台中,暗示该cookie没有设置或没有定义。我在想什么?

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?

推荐答案

由于您未发布的 csrfmiddlewaretoken ,所以Django的禁止你。 本文可以帮助你。

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

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

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