aryan aryan -4 years ago 139
Javascript Question

javascript post django form gives csrf error

I have a html form like:

<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.

Here I have included
csrf token
in the form. I have post this form form javascript and now it gives me
csrf verification failed
error.

What am I missing here ? Is it mandatory to create form from django' form class to use csrf token ?

Need help

My js looks like:

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

When I see request network, csrf token and comment are passed as request payload ..

Answer Source

This GitHub issue suggests that you have to include the credentials, so that the CSRF cookie is sent with the request.

fetch(url, {method: method, body: form_data, credentials: 'include'})
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download