Answer the question
In order to leave comments, you need to log in
AJAX, Django, CSRF: Why is there a 403 error?
A snippet of the index.html
file :
<div id = "task_adder">
<input type = "text" id = "task_text"><input type = "button" value = "Добавить задачу" id = "add">
</div>
<div id = "control_panel">
<input type = "button" value = "Удалить отмеченные" id = "delete">
<input type = "button" value = "Отметить выполненным" id = "done">
<input type = "button" value = "Вернуть в активное" id = "backward">
</div>
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(
{
url: to_url,
type: 'POST',
data: dict,
success: function()
{
$('#task_list').load('/ #task_list')
},
});
Answer the question
In order to leave comments, you need to log in
Actually csrf.js doesn't generate csrf token, it only reads it from cookies and puts it in HTTP header so that Django (CsrfViewMiddleware) can read it and protect against CSRF attack if the token is invalid.
Thus, to add this same csrf token to cookies, it is necessary that:
1. CsrfViewMiddleware must be specified in MIDDLEWARE_CLASSES
2. In the template, you need to insert the {% csrf_token %} tag into some form, if you do not have any suitable form, then use the ensure_csrf_cookie decorator ( https://docs.djangoproject.com/en/1.8/ref/csrf/#dj... ) to decorate view c index.html.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question