【问题标题】:403 Forbidden and request.method showing GET in django403 Forbidden 和 request.method 在 django 中显示 GET
【发布时间】:2017-02-24 14:45:00
【问题描述】:

我正在尝试使用 AJAX 将表单数据发送到应用程序。

Javascript 部分:

function submit_changes() {
var all_data = [A_list, B_list,C_list]
$.ajax({
    type: "POST",
    url: "/my_url/",
    contentType: "application/json",
    //dataType: 'json',
    //data:JSON.stringify(all_data),
data:{
    csrfmiddlewaretoken: "{{ csrf_token }}",        
    form:JSON.stringify(all_data),
},

  success: function() {
        alert('Data captured successfully');
        //window.location.reload();
    },
    error: function(){
        alert('Error in data capture')
        //window.location.reload();
    }
});
}

urls.py 有这个

urlpatterns=[url(r'^my_url/$',views.my_url_fn)]

views.py

def my_url_fn(request):
    print "*** request is ***",request
    if request.method == 'POST':
        print "request is POST"
        return Response(json.dumps(submit_changes(request)))
    elif request.method == 'GET':
        print "request is GET"
        return Response(json.dumps(get_already_present_data()),mimetype='application/json')
    else:
        print "neither post nor get"

html 代码中的表单部分是:

<div align="center">
  <form name="myForm" onSubmit="return 0">{% csrf_token %}    
    <input type="text" id="blah1" placeholder="Blah1&hellip;">
        <!-- few more fields -->
  </form> 
</div>
<div align='center'>
  <input id="submit_changes" type="button" align="middle" value="Submit Changes" onclick="submit_changes();" />
</div>

我已经在 html 中加载了 javascript。 我收到 403 禁止错误,并且 request.method 正在打印 GET。

我有两件事要问:

1)。为什么 request.method 是 POST 请求时是 GET?

2)。为什么我给了 csrf 令牌后仍然收到 403 禁止错误?

我已经搜索了很多并尝试了这些:在我的视图上方添加@csrf_exempt并将其导入为from django.views.decorators.csrf import csrf_exempt。没提升。我还尝试从我的settings.py 中的MIDDLEWARE 列表中删除django.middleware.csrf.CsrfViewMiddleware。还是没有进展!我这里还有一个问题。这是否意味着 settings.py 的变化没有得到反映?任何帮助将不胜感激!

【问题讨论】:

  • 您在代码更改后是否重新启动了服务器?
  • 只要检测到代码更改,它就会自行重启?!

标签: javascript python django mongodb django-mongodb-engine


【解决方案1】:

你可以试试这个

<script type="text/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');
    $(document).ready(function () {
        $.ajax({
            type: 'post',
            url: "{% url "url_to_view" %}",
            headers: {"X-CSRFToken": csrftoken},
            data: {id: "something to view"},
            success: function (response) {
                alert("success");
                });
            },
            failure: function (response) {
                alert(response.d);
            }
        });
    });
</script>

【讨论】:

  • 非常感谢。工作!
  • 哦,不。我还是有问题。它进入错误部分(failure: 不起作用,我认为它是error:)。可能的错误是什么?
  • 我发现了错误。我忘了在我的一个 python 代码中导入一些东西。现在 1.6 Django 一切正常。 :)
【解决方案2】:

您需要在 JavaScript 中执行类似的操作才能正确设置 csrf 令牌。它不需要部分数据,而是请求头

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRF-Token", CSRF_TOKEN);
        }
    }
});

在 django 中,您不需要执行 csrf_exempt,因为如果需要,上述代码会将 CSRF 令牌注入到每个 ajax 请求中。 (CSRF 有一个很好的理由,所以最好不要豁免它)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多