[英]javascript post django form gives csrf error
I have a html form like: 我有一个HTML表单,例如:
<form id="comment" action="{% url "url_name" ur.id %}" method="post">{% csrf_token %}
<textarea required="required" maxlength="255" rows="4" class="form-control" name="comment">
</textarea>
<button class="btn btn-default" onclick="add_comment(event)">Comment</button>
</form>
It is a html form and not django's
form. 它是html形式,而不是
django's
形式。
Here I have included csrf token
in the form. 在这里,我在表单中包含了
csrf token
。 I have post this form form javascript and now it gives me csrf verification failed
error. 我已经发布了此表单javascript,现在它给了我
csrf verification failed
错误。
What am I missing here ? 我在这里想念什么? Is it mandatory to create form from django' form class to use csrf token ?
从Django的表单类创建表单以使用csrf令牌是否是强制性的?
Need help 需要帮忙
My js looks like: 我的js看起来像:
function add_comment(event) {
event.preventDefault()
var form = document.getElementById('comment')
var url = form.action
var method = form.method
var form_data = new FormData(form)
fetch(url, {method: method, body: form_data})
}
and I am just rendering a template from my django view 我只是从django视图渲染模板
When I see request network, csrf token and comment are passed as request payload .. 当我看到请求网络时,csrf令牌和注释将作为请求有效负载传递。
这个GitHub问题建议您必须包含凭据,以便CSRF cookie与请求一起发送。
fetch(url, {method: method, body: form_data, credentials: 'include'})
I assume you're using AJAX to post the form. 我假设您正在使用AJAX发布表单。 When posting forms with Django using AJAX you need to add the following to your Javascript before submitting the AJAX request:
使用Django使用AJAX发布表单时,您需要在提交AJAX请求之前将以下内容添加到Javascript中:
$.ajaxSetup({
beforeSend: function(xhr, settings) {
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;
}
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
// Only send the token to relative URLs i.e. locally.
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
}
});
More info can be found at https://docs.djangoproject.com/en/1.10/ref/csrf/#ajax 可以在https://docs.djangoproject.com/en/1.10/ref/csrf/#ajax中找到更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.