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?
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With