javascript django ajax post 403 禁止
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13035412/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
django ajax post 403 forbidden
提问by psychok7
using django 1.4 im getting a 403 error when i try to do a post from my javascript do my django server. my get works fine though the problem is only with the post. also tried @csrf_exempt with no luck
使用 django 1.4 当我尝试从我的 javascript 做我的 django 服务器时,我收到 403 错误。尽管问题仅出在帖子上,但我的 get 工作正常。也试过@csrf_exempt 没有运气
UPDATE: I can Post now that i added {% csrf_token %}
, but the post response comes empty, although the GET comes correctly, any ideas?
更新:我现在可以发布,我添加了{% csrf_token %}
,但发布响应为空,尽管 GET 正确,有什么想法吗?
my django view:
我的 Django 视图:
@csrf_protect
def edit_city(request,username):
conditions = dict()
#if request.is_ajax():
if request.method == 'GET':
conditions = request.method
elif request.method == 'POST':
print "TIPO" , request.GET.get('type','')
#based on http://stackoverflow.com/a/3634778/977622
for filter_key, form_key in (('type', 'type'), ('city', 'city'), ('pois', 'pois'), ('poisdelete', 'poisdelete'), ('kmz', 'kmz'), ('kmzdelete', 'kmzdelete'), ('limits', 'limits'), ('limitsdelete', 'limitsdelete'), ('area_name', 'area_name'), ('action', 'action')):
value = request.GET.get(form_key, None)
if value:
conditions[filter_key] = value
print filter_key , conditions[filter_key]
#Test.objects.filter(**conditions)
city_json = json.dumps(conditions)
return HttpResponse(city_json, mimetype='application/json')
here is my javascript code :
这是我的 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');
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 (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
// Only send the token to relative URLs i.e. locally.
xhr.setRequestHeader("X-CSRFToken",
$('input[name="csrfmiddlewaretoken"]').val());
}
}
});
$.post(url,{ type : type , city: cityStr, pois: poisStr, poisdelete: poisDeleteStr, kmz: kmzStr,kmzdelete : kmzDeleteStr,limits : limitsStr, area_nameStr : area_nameStr , limitsdelete : limitsDeleteStr},function(data,status){
alert("Data: " + data + "\nStatus: " + status);
console.log("newdata" + data.area_name)
});
i have also tried from the site with no luck :
我也尝试过从网站上没有运气:
$.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);
}
}
});
what am i missing?
我错过了什么?
采纳答案by psychok7
got it working by adding {% csrf_token %}
somewhere within the form in my template
通过{% csrf_token %}
在我的模板中的表单中添加某处来使其工作
回答by Muhia NJoroge
you can actually pass this along with your data {csrfmiddlewaretoken:'{{csrf_token}}' } , it works all the time
您实际上可以将它与您的数据一起传递{csrfmiddlewaretoken:'{{csrf_token}}' },它一直有效
回答by woohoo
In my case I have a template in which I don't want to have a <form></form>
element. But I still want to make AJAX POST requests using jQuery.
就我而言,我有一个模板,我不想在其中包含<form></form>
元素。但我仍然想使用 jQuery 发出 AJAX POST 请求。
I got 403 errors, due to CSRF cookie being null, even if I followed the django docs (https://docs.djangoproject.com/en/1.5/ref/contrib/csrf/). The solution is in the same page, mentioning the ensure_csrf_cookie
decorator.
由于 CSRF cookie 为空,我收到了 403 错误,即使我遵循了 django 文档(https://docs.djangoproject.com/en/1.5/ref/contrib/csrf/)。解决方案在同一页面中,提到了ensure_csrf_cookie
装饰器。
My CSRF cookie did get set when I added this at the top of my views.py
:
当我将它添加到我的顶部时,我的 CSRF cookie 确实设置好了views.py
:
from django.views.decorators.csrf import ensure_csrf_cookie
@ensure_csrf_cookie
Also, please note that in this case you do not needthe DOM element in your markup / template: {% csrf_token %}
另外,请注意,在这种情况下,您的标记/模板中不需要DOM 元素:{% csrf_token %}