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?
A better solution is to generate the code of the js file from a view/template.
Then, in the view you can set the csrf token up in the context like so...
Then, in the template, you can use
{{ csrf_token }}
to get the raw value of the csrf token, and then use that to build a hidden field into your form with the namecsrfmiddlewaretoken
.This will use the csrf token or auto generate a new one if needed. It will handle all form submits on the page. If you have off-site forms you'll need to make sure they don't run this code.
requires jQuery 1.7+
This may not be ideal, but it was the fastest solution for me. In my main template at the bottom of the "body", I added a javascript function to my library.
The easiest way is to create a hidden form on your page using django that doesn't do anything. Then use JavaScript to fetch the form and specifically the token input out of the form. Lastly, insert or copy that token input into the form you are dynamically generating.
Here are two examples of how you might publish the token for JavaScript.
or
Does the view you are
POST
ing to also respond toGET
? In that the JS code can make aGET
request to the view in question and parse the output to extract the CSRF token. My JS-fu is weak and I am not sure how best you can do the parsing from the client side.For a broadly related example see this question. In this case the user was attempting to
POST
using a Python script and failing for the same reason. The solution was the same, except he had to do it from a Python script rather than JavaScript.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):
(edit: Ext already has cookie reading function, no need to duplicate it)