views:

131

answers:

3

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?

+1  A: 

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.

matt snider
Can you provide an example?
Huuuze
Why the down vote?
Török Gábor
@Huuuze: put `{csrf_token}` in the template somewhere, and parse it with JavaScript during form building.
Török Gábor
A: 

Does the view you are POSTing to also respond to GET? In that the JS code can make a GET 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.

Manoj Govindan
A: 

The best solution I've found for my particular case is to simply use the @csrf_exempt decorator, detailed here:

http://docs.djangoproject.com/en/dev/ref/contrib/csrf/#exceptions

Huuuze