[英]Ajax post to Django view CSRF forbidden
CSRF is preventing me from posting to a Django view. CSRF阻止我发布到Django视图。
I'm following a solution from the official django docs and this question: Django CSRF check failing with an Ajax POST request . 我正在遵循官方django文档和以下问题的解决方案: Django CSRF检查失败,并带有Ajax POST请求 。 Everything should be setup fine but it fails when it executes. 一切都应该设置正确,但是执行失败。
My setup is as follows, 我的设置如下
jQuery post method: jQuery发布方法:
var send_data = { 'name': place.name, 'address': address};
var csrftoken = $.cookie('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
crossDomain: false, // obviates need for sameOrigin test
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type)) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
$.ajax({ url: '/results/',
type: 'POST',
data: send_data,
success: function(response) {
$('#results').html(response);
}
});
Django view: Django视图:
def results(request):
return render(request, "stamped/restaurant.html")
Urls.py Urls.py
urlpatterns = patterns('',
url(r'^$', views.home, name='home'),
url(r'results/', views.results, name='results'),
)
Everything should be fine. 一切都应该没问题。 Any idea on what I'm missing? 对我缺少的东西有任何想法吗?
Ive also tired: 我也累了:
Unable to jQuery $.post data to a view in django due to CSRF 由于CSRF无法将jQuery $ .post数据发送到Django中的视图
Jquery Ajax Post to Django View jQuery Ajax发布到Django视图
Error output: 错误输出:
UPDATE: 更新:
The code in this question is correct. 这个问题中的代码是正确的。 It seems my browser cache needed to be emptied. 看来我的浏览器缓存需要清空。
In your question you're missing the template tag {{ csrf_token }}
in your template. 在您的问题中,您缺少模板中的模板标签{{ csrf_token }}
。
From the docs: 从文档:
If your view is not rendering a template containing the csrf_token template tag, Django might not set the CSRF token cookie. 如果您的视图未呈现包含csrf_token模板标记的模板,则Django可能未设置CSRF令牌cookie。 This is common in cases where forms are dynamically added to the page. 在将表单动态添加到页面的情况下,这很常见。 To address this case, Django provides a view decorator which forces setting of the cookie: ensure_csrf_cookie(). 为了解决这种情况,Django提供了一个视图装饰器来强制设置cookie:sure_csrf_cookie()。
Solution: 解:
Empty your browser cache. 清空浏览器缓存。 The above code is correct. 上面的代码是正确的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.