Skip to content

Django CSRF Migration

2010 June 2
tags:
by pk

Like many of you, I am migrating all my Django sites to Django 1.2.1. For sites that are currently in production, I am doing the slow migration route. Just trying to get the site up with 1.2 without using any of the new features yet.

One thing that I ran into is the new CSRF support. If you were not using it before, there really is no change with one exception — all the generic views and admin views requires CSRF protection. This means that if you are using django login view django.contrib.auth.views.login , you have to make sure that any wrapper or custom templates support CSRF.

Specifically:

  1. If you use your own login template, you must add {% csrf_token %} to the end of the openning form tag.
  2. If you wrap the call to login with your own view, you must add the csrf decorator @csrf_protect to your view, after importing django.views.decorators.csrf.csrf_protect
  3. If you use the django.contrib.auth.logout view to redisplay a login form, you have to replace that with a wrapper because the auth.logout view does NOT add the csrf token. (Updated)

Otherwise django will send you a 403 error when you try to login.

Share and Enjoy:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • LinkedIn
  • Posterous
  • Tumblr
  • Twitter
2 Responses leave one →
  1. June 3, 2010

    Interesting, I knew about the first point by encountering a CSRF error when my login template didn’t include {% csrf_token %}, but I didn’t know about the second.

    Thanks, I’ll keep it in mind!

    Rob

  2. Thom permalink
    September 8, 2010

    I am receiving the CSRF 403 when I try to login to the admin and I have not done any customization to the admin files or wrapped them at all. Any ideas?

Leave a Reply

Note: You can use basic XHTML in your comments. Your email address will never be published.

Subscribe to this comment feed via RSS