Cross Site Request Forgery protection in Django

[This is pretty old news but I am clearing out my pile of unposted content]

Someone updated Django on a server I use, so I finally had to update the web applications on it to support Django's new Cross Site Request Forgery protection, I had been putting it off since I don't really need the protection for these simple sites. However, it is quicker to enable it than disable it. Sorting it out is simple.

Stick the following into the MIDDLEWARE_CLASSES:

'django.middleware.csrf.CsrfViewMiddleware'

Then grep your application templates for <form tags. If the form is method="post" (i.e. not get), then shove {% csrf_token %} into the template after the <form> tag.

Lastly, the views that use the templates you changed, need to use RequestContext if they are not already. So put the following import in the relevant views.py file.

from django.template import RequestContext

Then in the render_to_response function that you are returning, add the following keyword argument:

context_instance=RequestContext(request)

How about Global Thermonuclear War? Wouldn't you prefer a good game of chess? Powered by zpress