错误:“CSRF验证失败。请求中止。“当使用jquery ajax和Django时

时间:2021-11-05 06:59:05

in template:

<script type="text/javascript">
        $.ajax({
             type:"POST",
             url:"{% url DrHub.views.ajxTest %}",
             data: {
                    'start': $('#id_startTime').val(),
                    'end': $('#id_endTime').val(),
                    'csrfmiddlewaretoken': '{{ csrf_token }}'
             },
             success: function(data){
                 alert(data);
             }
        });
</script>
.
.
.
<form method='POST' action=".">
    {% csrf_token %}
    <input type="text id="id_startTime" />
    <input type="text id="id_endTime" />
    <input type="submit" value="send" />
</form>

in views:

def ajxTest(request):
   if request.is_ajax():
      if request.method == 'POST':
         return HttpResponse(json.dumps({'message' : 'awesome'},ensure_ascii=False), mimetype='application/javascript')

in settings.py:

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.locale.LocaleMiddleware',
)

when submitting form I have this error:CSRF verification failed. Request aborted.

提交表单时出现此错误:CSRF验证失败。请求中止。

I searched alot but none of suggested solutions worked for me!

我搜索了很多,但没有一个建议的解决方案适合我!

like : Django CSRF check failing with an Ajax POST request

像:Django CSRF检查失败的Ajax POST请求

and : Ajax Post in Django framework?

和:Django框架中的Ajax Post?

I refreenced to a js file with this content:

我用这个内容重新刷新了一个js文件:

$.ajaxSetup({ 
     beforeSend: function(xhr, settings) {
         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;
         }
         if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
             // Only send the token to relative URLs i.e. locally.
             xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
         }
     } 
});

but this didn't work,too!

但这也行不通!

And I saw a solution that say use ajaxSetup instead of ajaxSend to post data,how can I do this?

我看到一个解决方案,说使用ajaxSetup而不是ajaxSend来发布数据,我该怎么做?

6 个解决方案

#1


5  

You should pull the csrfmiddlewaretoken from the dom element:

你应该从dom元素中提取csrfmiddlewaretoken:

{'csrfmiddlewaretoken':$( "#csrfmiddlewaretoken" ).val()}

{'csrfmiddlewaretoken':$(“#csrfmiddlewaretoken”)。val()}

The above is exactly what I do in several places and it works.

以上就是我在几个地方做的事情,它的确有效。

Edit just to add some clarity drawing from your material:

编辑只是为了从材料中添加一些清晰度图:

<script type="text/javascript">
    $.ajax({
         type:"POST",
         url:"{% url DrHub.views.ajxTest %}",
         data: {
                'start': $('#id_startTime').val(),
                'end': $('#id_endTime').val(),
                'csrfmiddlewaretoken':$( "#csrfmiddlewaretoken" ).val()
         },
         success: function(data){
             alert(data);
         }
    });
</script>

#2


2  

having this a refrence to a js file with this content was my solution:

有这个内容的js文件的参考是我的解决方案:

jQuery(document).ajaxSend(function(event, xhr, settings) {
    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;
    }
    function sameOrigin(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));
    }
    function safeMethod(method) {
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});

#3


2  

There's also another shortcut to this. I wouldn't know if the security thing here is of so much value and importance. I ran into this problem but there seems to be a lot of hacks around this that end up trying to submit the csrftoken from an existing cookie. I don't know what would happen if this cookie does not exist or was not set.

还有另一个捷径。我不知道这里的安全问题是否具有如此重要的价值和重要性。我遇到了这个问题,但似乎有很多黑客攻击,最终试图从现有的cookie提交csrftoken。我不知道如果这个cookie不存在或没有设置会发生什么。

My approach was to add a @csrf_exempt to the view that processes the ajax post. You import the csrf_exempt from django.views.decorators.csrf

我的方法是将@csrf_exempt添加到处理ajax帖子的视图中。您从django.views.decorators.csrf导入csrf_exempt

Like this:

from django.views.decorators.csrf import csrf_exempt

And than, from the view method:

而且,从视图方法:

@csrf_exempt
def the_method_to_be_called(request):

...

see this link

看到这个链接

#4


0  

Please add the csrfmiddlewaretoken as csrfmiddlewaretoken: {% csrf_token %} in your js.

请在您的js中将csrfmiddlewaretoken添加为csrfmiddlewaretoken:{%csrf_token%}。

<script type="text/javascript">
        $.ajax({
             type:"POST",
             url:"{% url DrHub.views.ajxTest %}",
             data: {
                    'start': $('#id_startTime').val(),
                    'end': $('#id_endTime').val(),
                    'csrfmiddlewaretoken': '{% csrf_token %}'
             },
             success: function(data){
                 alert(data);
             }
        });
</script>

#5


0  

in HTML(template)

{% csrf_token %}

in JS

$.ajax({
    type: "POST",
    url: '/brand-admin/publish_article/',
    data: {
      'article_id': article_id,
      'csrfmiddlewaretoken':$( "input[name='csrfmiddlewaretoken']" ).val()
    },
    dataType: 'json',
    success: function (data) {
      console.log(data);
    }
  });

#6


0  

If the {% csrf_token %} is in your form on your template:

如果您的模板中的表单中包含{%csrf_token%}:

<form id="the-form" autocomplete="off">
    {% csrf_token %}
    <input type="text" name="q">
    <input type="submit" value="Submit">
</form>

you should be able to send it up using:

你应该能够使用以下方式发送它:

$("#the-form").submit(function(e){
  e.preventDefault();
  $.ajax({
    type: "POST",
    url: "/post-url",
    data: $("#the-form").serialize(),
    success: function(data){
      console.log(data);
    }
  });
});

#1


5  

You should pull the csrfmiddlewaretoken from the dom element:

你应该从dom元素中提取csrfmiddlewaretoken:

{'csrfmiddlewaretoken':$( "#csrfmiddlewaretoken" ).val()}

{'csrfmiddlewaretoken':$(“#csrfmiddlewaretoken”)。val()}

The above is exactly what I do in several places and it works.

以上就是我在几个地方做的事情,它的确有效。

Edit just to add some clarity drawing from your material:

编辑只是为了从材料中添加一些清晰度图:

<script type="text/javascript">
    $.ajax({
         type:"POST",
         url:"{% url DrHub.views.ajxTest %}",
         data: {
                'start': $('#id_startTime').val(),
                'end': $('#id_endTime').val(),
                'csrfmiddlewaretoken':$( "#csrfmiddlewaretoken" ).val()
         },
         success: function(data){
             alert(data);
         }
    });
</script>

#2


2  

having this a refrence to a js file with this content was my solution:

有这个内容的js文件的参考是我的解决方案:

jQuery(document).ajaxSend(function(event, xhr, settings) {
    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;
    }
    function sameOrigin(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));
    }
    function safeMethod(method) {
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});

#3


2  

There's also another shortcut to this. I wouldn't know if the security thing here is of so much value and importance. I ran into this problem but there seems to be a lot of hacks around this that end up trying to submit the csrftoken from an existing cookie. I don't know what would happen if this cookie does not exist or was not set.

还有另一个捷径。我不知道这里的安全问题是否具有如此重要的价值和重要性。我遇到了这个问题,但似乎有很多黑客攻击,最终试图从现有的cookie提交csrftoken。我不知道如果这个cookie不存在或没有设置会发生什么。

My approach was to add a @csrf_exempt to the view that processes the ajax post. You import the csrf_exempt from django.views.decorators.csrf

我的方法是将@csrf_exempt添加到处理ajax帖子的视图中。您从django.views.decorators.csrf导入csrf_exempt

Like this:

from django.views.decorators.csrf import csrf_exempt

And than, from the view method:

而且,从视图方法:

@csrf_exempt
def the_method_to_be_called(request):

...

see this link

看到这个链接

#4


0  

Please add the csrfmiddlewaretoken as csrfmiddlewaretoken: {% csrf_token %} in your js.

请在您的js中将csrfmiddlewaretoken添加为csrfmiddlewaretoken:{%csrf_token%}。

<script type="text/javascript">
        $.ajax({
             type:"POST",
             url:"{% url DrHub.views.ajxTest %}",
             data: {
                    'start': $('#id_startTime').val(),
                    'end': $('#id_endTime').val(),
                    'csrfmiddlewaretoken': '{% csrf_token %}'
             },
             success: function(data){
                 alert(data);
             }
        });
</script>

#5


0  

in HTML(template)

{% csrf_token %}

in JS

$.ajax({
    type: "POST",
    url: '/brand-admin/publish_article/',
    data: {
      'article_id': article_id,
      'csrfmiddlewaretoken':$( "input[name='csrfmiddlewaretoken']" ).val()
    },
    dataType: 'json',
    success: function (data) {
      console.log(data);
    }
  });

#6


0  

If the {% csrf_token %} is in your form on your template:

如果您的模板中的表单中包含{%csrf_token%}:

<form id="the-form" autocomplete="off">
    {% csrf_token %}
    <input type="text" name="q">
    <input type="submit" value="Submit">
</form>

you should be able to send it up using:

你应该能够使用以下方式发送它:

$("#the-form").submit(function(e){
  e.preventDefault();
  $.ajax({
    type: "POST",
    url: "/post-url",
    data: $("#the-form").serialize(),
    success: function(data){
      console.log(data);
    }
  });
});