CSRF验证失败。请求被中止。// Dajaxice,Ajax

2024-09-28 20:53:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Daxice库在我的Django应用程序中创建AJAX调用。 当我在表单上创建POST方法时,我得到了上面提到的错误:

Forbidden (403)
CSRF verification failed. Request aborted.

我的设置.py有:

^{pr2}$

我的网址.py在

from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from dajaxice.core import dajaxice_autodiscover, dajaxice_config
dajaxice_autodiscover()

urlpatterns = patterns('',
    url(dajaxice_config.dajaxice_url, include('dajaxice.urls')),
    url(r'^$', 'apps.views.home'),
)

urlpatterns += staticfiles_urlpatterns()

我的视图.py公司名称:

from django.http import HttpResponse
from django.template import loader, Context

from django.core.context_processors import csrf

def home(request):
    t = loader.get_template('index.html')
    html = t.render(Context( ))
    return HttpResponse(html)

我的模板索引.html公司名称:

{% load dajaxice_templatetags %}

<html>
  <head>
    <title>My base template</title>

    <script src="http://code.jquery.com/jquery-latest.min.js"
        type="text/javascript"></script>

    {% dajaxice_js_import %}

    <script type="text/javascript">

    function shout(data){
        alert(data.message)

    }

    </script>
  </head>
  <body>

    <form method="POST" action="">{% csrf_token %}
        Page: <input type="text" name="page"><br>
        From: <input type="text" name="from"> (From < To) <br>
        To: <input type="text" name="to"> (returns results before that day)<br>
        <input type="submit" onclick="Dajaxice.apps.hello(shout);" value="Submit">
    </form>

    <br>
    <br>

    <input type="button" onclick="Dajaxice.apps.hello(shout);" value="Get message from server!">

   </body>
</html>

还有我的阿贾克斯.py公司名称:

import simplejson
from dajaxice.decorators import dajaxice_register

@dajaxice_register(method='GET')
@dajaxice_register(method='POST', name='other_post')
def hello(request):
    return simplejson.dumps({'message':'Hello from Python!'})

如果我点击按钮,消息就会被提醒。当我提交表格时,我得到了这个错误。我怎样才能修好它?在

最后,我相信我已经修复了调试页面中CSRF显示的所有可能性:

In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure:
Your browser is accepting cookies.
The view function uses RequestContext for the template, instead of Context.
In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.
If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data.

Tags: djangotextfrompybrimporturlinput
3条回答

Dajaxice为您处理CSRF,在发送代码之前不需要任何自定义jQuery。在

但您需要授予Dajaxice访问CSRF cookie的权限。因此:

确保在您的设置.py!

好吧,我想我明白了。在线:

<form>
...
<input type="submit" onclick="Dajaxice.apps.hello(shout);" value="Submit"></form>
...
</form>

如果typebutton,那么它可以工作。它应该与服务器请求的submit行为有关。我不是解释为什么会发生这种情况的专家,所以如果有人能解释,我很乐意投赞成票。在

根据docs,如果先运行此脚本,则可以在每个ajax post请求上发送csrf令牌:

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

它是用jquery编写的。如果您想要香草js,请访问docs

相关问题 更多 >