[Django]-Csrf token error in dynamic form in django

3👍

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');
👤fips

1👍

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.

Leave a comment