Reputation: 11468
I know the question similar to this has been asked before before I could not derive workable solution for my problem using those answers.
I have a page which has a form A and lots of checkboxes. The form and related checkboxes is created through Django Templates. I created a new form B via javascript from the the input values of the form A created by Django Template. Django is not accepting my new form B due to csrf_token error. Can somebody show me how to extract csrf token from the form A rendered by django and use it as csrf token for the dynamically created javascript form?
Upvotes: 3
Views: 1395
Reputation: 4379
You can include the csrf token in the data your posting.
You can either extract it from the hidden field in the html form:
<input type="hidden" name="csrfmiddlewaretoken" value="IxwFarTrerVBZbVDX0elVHUEbh0YH58j">
using a jquery selector:
var token = $('input[name="csrfmiddlewaretoken"]').val();
Or if you prefer plain js as you have mentioned you can use this function to extract it from the document cookies:
function getCookie(name) {
var v = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
return v ? v[2] : null;
}
var token = getCookie('csrftoken');
Upvotes: 3
Reputation: 161
I think a simpler approach would be to use cookies. A csrf token is just a cookie whose value you can retrieve. Kindly look at the section on Ajax
and see if it can offer any help https://docs.djangoproject.com/en/1.9/ref/csrf/#ajax.
var csrftoken = Cookies.get('csrftoken');
Doing that using the javascript cookie library should ideally help you to retrieve the csrf token.
Upvotes: 1