How do I include Django 1.2's CSRF token in a Javascript-generated HTML form?

前端 未结 6 1706
感动是毒
感动是毒 2020-12-09 05:45

I recently upgraded to Django 1.2.3 and my upload forms are now broken. Whenever I attempt to upload, I receive a \"CSRF verification failed. Request aborted.\" error messag

6条回答
  •  情书的邮戳
    2020-12-09 06:23

    Another option would be to adapt the cookie/header based solution shown in the Django docs with Ext - preferable if you have a lot of templates and don't want to change every single one.

    Just drop the following snippet in your overrides.js (or wherever you put global modifications):

    Ext.Ajax.on('beforerequest', function (conn, options) {
       if (!(/^http:.*/.test(options.url) || /^https:.*/.test(options.url))) {
         if (typeof(options.headers) == "undefined") {
           options.headers = {'X-CSRFToken': Ext.util.Cookies.get('csrftoken')};
         } else {
           options.headers.extend({'X-CSRFToken': Ext.util.Cookies.get('csrftoken')});
         }                        
       }
    }, this);
    

    (edit: Ext already has cookie reading function, no need to duplicate it)

提交回复
热议问题