我正在使用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.
Dajaxice为您处理CSRF,在发送代码之前不需要任何自定义jQuery。在
但您需要授予Dajaxice访问CSRF cookie的权限。因此:
确保在您的设置.py!
好吧,我想我明白了。在线:
如果
type
是button
,那么它可以工作。它应该与服务器请求的submit
行为有关。我不是解释为什么会发生这种情况的专家,所以如果有人能解释,我很乐意投赞成票。在根据docs,如果先运行此脚本,则可以在每个ajax post请求上发送csrf令牌:
它是用jquery编写的。如果您想要香草js,请访问docs
相关问题 更多 >
编程相关推荐