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

Huuuze picture Huuuze · Sep 21, 2010 · Viewed 12.4k times · Source

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

After reading Django's documentation on this subject, it states that I need to add the {% csrf_token %} template tag within the HTML <form> in my template. Unfortunately, my <form> is generated via JavaScript (specifically, ExtJs's "html" property on a Panel).

Long story short, how do I add the required CSRF token tag to my <form> when my <form> is not included in a Django template?

Answer

chrisv picture chrisv · Mar 30, 2011

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)