【发布时间】:2017-10-24 09:19:59
【问题描述】:
所以我开发了一个 django 应用程序,我正在尝试向 Postgresql 发布一些内容,我知道 CSRF 令牌在对视图发出 ajax 请求期间是必需的,我已经这样做了,这是我的 csrf.js ,我已经包含在我的标题模板中
// using jQuery
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));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
这是我在模板中提出的 ajax 请求
$.ajax({type: 'POST',
url: '/sample/saveData/', // some data url
data: {param: workHours.length, param1: $(getDayName[i]).text(),param2: bla,param3: bla1,param4: bla2},
// some params
success: function (response) { // callback
if (response.result === 'OK') {
if (response.data && typeof(response.data) === 'object') {
// do something with the successful response.data
// e.g. response.data can be a JSON object
}
} else {
window.alert(response.result);
}
}
});
这是我的看法,希望对你有帮助
def saveData(request):
if request.is_ajax():
# extract your params (also, remember to validate them)
param = request.POST.get('param', None)
param1 = request.POST.get('param1', None)
param2 = request.POST.get('param2', None)
param3 = request.POST.get('param3', None)
param4 = request.POST.get('param4', None)
stringData=datetime.datetime.now().strftime('%H:%M:%S')+" ("+param1+")"
#another_param = request.POST.get('another param', None)
#return HttpResponse(param, mimetype)
p = Post(user="John",weekOfthemonth=param2 ,didAttend='Yes',date=stringData,numofHours=param,logIn=param3,logOut=param4)
p.save()
return HttpResponseBadRequest()
【问题讨论】:
-
有什么问题?向我们展示您的错误信息,或出现什么问题。
-
不要在代码中告诉我们您的问题。请更新您的问题:)
-
@dirkgroten 这就是我得到的“禁止 (403) CSRF 验证失败。请求中止。您看到此消息是因为此站点在提交表单时需要 CSRF cookie。此 cookie 是必需的出于安全原因,以确保您的浏览器不会被第三方劫持。如果您已将浏览器配置为禁用 cookie,请至少为该站点或“同源”请求重新启用它们。”跨度>
-
@mohammedqudah 我不确定你想问什么??
-
@sam 我可以使用 csrf_exempt 解决这个问题,但这可能不安全?
标签: jquery ajax django postgresql