Quick shell command to add CSRF token

To get the benefit of Django 1.2’s new CSRF protection, all POST forms will need a special token. Here is a quick command that runs through templates adding the token:

find . -type f -name "*.html" -exec sed -i \
's|\(<form[^>]*method="post"[^>]*>\)\({% csrf_token %}\)\?|\1{% csrf_token %}|g' \
{} \;

CSRF docs? TLDR

I recently ported my handful of sites to 1.2 and was irked by both the invasiveness of the changes required by the CSRF tools and all the seeming caveats in the docs. So here’s the barebones what you need to do:

  1. any form that does a POST, make sure a {% csrf_token %} in there
  2. add ‘django.middleware.csrf.CsrfViewMiddleware’ to your middleware settings

Ignore Csrf

Maybe you don’t want to deal with Csrf at all. Add the following middleware above (or before) your Csrf middleware:

class IgnoreCsrfMiddleware(object):
    def process_request(self, request):
        request.csrf_processing_done = True

Read full article at “charlesleifer.com: Entries tagged with "django"”

Leave a comment