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

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

问题描述

我正在尝试将 jquery 集成到我使用 Django 框架制作的 Web 应用程序中.然而,我很难尝试通过简单的 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>

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

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

我已尝试遵循 上的官方文档跨站点请求伪造保护,并查看了解决类似问题的几个计算器溢出问题.我在我的 html 模板文件中包含了 {% csrf_token %} 但它似乎仍然不起作用.我在控制台中收到一条错误消息,提示 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)   

如何将 result 变量与我的 http 响应一起传递并让 ajax 调用顺利运行?任何帮助深表感谢.

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 令牌与我的发布请求一起传递.所以根据文档,我将以下代码添加到我的模板 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页面时,在控制台得到null,提示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天全站免登陆