Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 306
Huuuze Avatar asked Sep 21 '10 21:09

Huuuze


People also ask

Where do I put CSRF token in HTML?

Place the field containing the CSRF token as early as possible within the HTML file. Place the field that contains the token before any non-hidden fields and before any places where user-controllable data is embedded.

How do I add a CSRF token?

csrf token html form Add a viewport meta tag to the document head to set the width of the layout viewport equal to the width of the device and set the initial scale of the viewport to 1.0.

How does Django generate CSRF token?

The CSRF token is like an alphanumeric code or random secret value that's peculiar to that particular site. Hence, no other site has the same code. In Django, the token is set by CsrfViewMiddleware in the settings.py file. A hidden form field with a csrfmiddlewaretoken field is present in all outgoing requests.


1 Answers

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)

like image 197
chrisv Avatar answered Sep 23 '22 03:09

chrisv