【问题标题】:django ajax post 403 forbiddendjango ajax 发布 403 被禁止
【发布时间】:2012-10-13 16:16:49
【问题描述】:

使用 django 1.4 时,当我尝试从我的 javascript 发布我的 django 服务器时出现 403 错误。尽管问题仅出在帖子上,但我的 get 工作正常。也尝试了@csrf_exempt 没有运气

更新:我现在可以发布我添加了 {% csrf_token %} ,但发布响应是空的,虽然 GET 正确,有什么想法吗?

我的 Django 视图:

@csrf_protect
def edit_city(request,username):
    conditions = dict()

    #if request.is_ajax():
    if request.method == 'GET':
        conditions = request.method

    elif request.method == 'POST':
        print "TIPO" , request.GET.get('type','')       
        #based on http://stackoverflow.com/a/3634778/977622     
        for filter_key, form_key in (('type',  'type'), ('city', 'city'), ('pois', 'pois'), ('poisdelete', 'poisdelete'), ('kmz', 'kmz'), ('kmzdelete', 'kmzdelete'), ('limits', 'limits'), ('limitsdelete', 'limitsdelete'), ('area_name', 'area_name'), ('action', 'action')):
            value = request.GET.get(form_key, None)
            if value:
                conditions[filter_key] = value
                print filter_key , conditions[filter_key]

        #Test.objects.filter(**conditions)
    city_json = json.dumps(conditions)

    return HttpResponse(city_json, mimetype='application/json')

这是我的 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');

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
function sameOrigin(url) {
    // test that a given url is a same-origin URL
    // url could be relative or scheme relative or absolute
    var host = document.location.host; // host + port
    var protocol = document.location.protocol;
    var sr_origin = '//' + host;
    var origin = protocol + sr_origin;
    // Allow absolute or scheme relative URLs to same origin
    return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
        (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
        // or any other URL that isn't scheme relative or absolute i.e relative.
        !(/^(\/\/|http:|https:).*/.test(url));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
    if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
        // Only send the token to relative URLs i.e. locally.
        xhr.setRequestHeader("X-CSRFToken",
                             $('input[name="csrfmiddlewaretoken"]').val());
    }
}
});

$.post(url,{ type : type , city: cityStr, pois: poisStr, poisdelete: poisDeleteStr, kmz: kmzStr,kmzdelete : kmzDeleteStr,limits : limitsStr, area_nameStr : area_nameStr , limitsdelete : limitsDeleteStr},function(data,status){
                    alert("Data: " + data + "\nStatus: " + status);
                    console.log("newdata" + data.area_name)
                });

我也试过从网站上没有运气:

$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) {
            // Send the token to same-origin, relative URLs only.
            // Send the token only if the method warrants CSRF protection
            // Using the CSRFToken value acquired earlier
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});

我错过了什么?

【问题讨论】:

  • 您是否设置了 DEBUG = True?转到 Chrome 开发工具 -> 网络,然后单击失败的请求。您在“预览”或“响应”选项卡中收到什么消息?
  • 我收到“CSRF 验证失败。请求中止。”
  • 奇怪的是现在我的回复是空的,知道为什么吗? get 仍然可以正常工作

标签: javascript ajax django http-post http-status-code-403


【解决方案1】:

您实际上可以将它与您的数据一起传递 {csrfmiddlewaretoken:'{{csrf_token}}' } ,它一直有效

【讨论】:

  • 令牌的名称应该是“csrfmiddlewaretoken”,而不是“csrftoken”。 (Django 1.4)
【解决方案2】:

就我而言,我有一个模板,我不想在其中包含&lt;form&gt;&lt;/form&gt; 元素。但我仍然想使用 jQuery 发出 AJAX POST 请求。

由于 CSRF cookie 为空,我得到了 403 错误,即使我遵循了 django 文档 (https://docs.djangoproject.com/en/1.5/ref/contrib/csrf/)。解决方案在同一页面中,提到了ensure_csrf_cookie 装饰器。

当我在views.py 顶部添加这个时,我的 CSRF cookie 确实被设置了:

from django.views.decorators.csrf import ensure_csrf_cookie
@ensure_csrf_cookie

另外,请注意,在这种情况下,您不需要标记/模板中的 DOM 元素:{% csrf_token %}

【讨论】:

  • 谢谢!我必须在我的类定义之前使用以下内容,因为我使用的是基于类的视图:@method_decorator(ensure_csrf_cookie, name='update')
【解决方案3】:

通过在我的模板中的表单中的某处添加{% csrf_token %} 使其工作

【讨论】:

  • csrf_token 是一个反跨站点请求伪造 (en.wikipedia.org/wiki/Cross-site_request_forgery) 令牌,并且是必需的,因为“django.middleware.csrf.CsrfViewMiddleware”在您的 settings.py 的 MIDDLEWARE_CLASSES 部分中定义.
猜你喜欢
  • 2014-01-25
  • 2019-08-10
  • 1970-01-01
  • 2019-05-08
  • 2015-07-30
  • 2013-08-24
  • 2021-05-07
  • 2012-08-13
  • 2018-11-03
相关资源
最近更新 更多