简体   繁体   中英

csrf token error in dynamic form in django

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM