简体   繁体   English

403 Forbidden和request.method在Django中显示GET

[英]403 Forbidden and request.method showing GET in django

I am trying to send a form data to an app using AJAX. 我正在尝试使用AJAX将表单数据发送到应用程序。

Javascript part: 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 has this urls.py有这个

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

views.py 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"

Form part from html code is: 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>

I have loaded the javascript in html. 我已经在html中加载了javascript。 I am getting 403 forbidden error and the request.method is printing GET. 我收到403禁止错误,request.method正在打印GET。

I have two things to ask : 我有两件事要问:

1). 1)。 Why is request.method GET when it is a POST request? 为什么request.method是POST请求时GET?

2). 2)。 Why am I still getting 403 forbidden error even after giving csrf token? 为什么即使给了csrf令牌,我仍然会收到403禁止错误?

I have searched a lot and tried these: Adding @csrf_exempt above my view and importing it as from django.views.decorators.csrf import csrf_exempt . 我进行了很多搜索并尝试了以下操作:在@csrf_exempt上方添加@csrf_exempt并将其from django.views.decorators.csrf import csrf_exempt No improvement. 没有得到改善。 I have also tried removing django.middleware.csrf.CsrfViewMiddleware from MIDDLEWARE list in my settings.py. 我也尝试django.middleware.csrf.CsrfViewMiddleware settings.py中的MIDDLEWARE列表中删除django.middleware.csrf.CsrfViewMiddleware Still no progress! 还是没有进步! I have another question here. 我在这里还有另一个问题。 Does this mean changes in settings.py are not getting reflected ? 这是否意味着settings.py中的更改没有得到体现? Any help would be greatly appreciated ! 任何帮助将不胜感激 !

You need to do something like this in JavaScript to correctly set the csrf token. 您需要在JavaScript中执行类似的操作才能正确设置csrf令牌。 It doesn't need to part of the data, but rather the request headers 它不需要部分数据,而是请求标头

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

In django you don't need to do a csrf_exempt as the above code will inject the CSRF token into every ajax request, if needed. 在django中,您不需要执行csrf_exempt,因为上面的代码会将CSRF令牌注入每个ajax请求(如果需要)。 (there is a very good reason why CSRF is there so it's best not to exempt it) (存在CSRF的理由非常充分,因此最好不要豁免它)

You can try this 你可以试试这个

<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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM