django-safeform 2.0.0

CSRF protection for Django forms

  Add it to your Download Basket!

 Add it to your Watch List!


Rate it!
send us
an update
BSD License 
Simon Willison
ROOT \ Internet \ HTTP (WWW)
django-safeform offers CSRF protection for Django implemented at the form level - no middleware required.

There are two steps to protecting a django.forms form:

1. Wrap it with the SafeForm class decorator. This adds a hidden csrf_token field to it along with validation logic for checking if that token has the correct value. It also changes the signature of the form class slightly, see example below.
2. Apply the @csrf_protect middleware to the view containing the form. This ensures that a _csrf_cookie is correctly set.

Run "./ runserver" in the examples folder to start a Django server demonstrating the functionality of the library. Use "./ test" in the same directory to run the unit tests.

Example usage:

    from django import forms
    from django.http import HttpResponse
    from django.shortcuts import render_to_response
    from django_safeform import SafeForm, csrf_protect

    class ChangePasswordForm(forms.Form):
        password = forms.CharField(widget = forms.PasswordInput)
        password2 = forms.CharField(widget = forms.PasswordInput)

    ChangePasswordForm = SafeForm(ChangePasswordForm)

    def change_password(request):
        form = ChangePasswordForm(request) # A
        if form.is_valid(): # B
            # ... change the user's password here
            return HttpResponse('Thank you')
        return render_to_response('change_password.html', {
            'form': form,

A: Note that we pass the whole request object to the constructor, instead of just passing request.POST.

B: A pleasant side-effect of SafeForm is that you no longer need to check to see if request.method == 'POST' in order to decide whether or not to bind a form to a set of input data - SafeForm handles this for you.

Custom form templates:

If your template uses one of the form rendering helper methods such as {{ form.as_p }} the hidden csrf_token field will be output automatically. If you are rendering the form using a custom template you will need to remember to output that field in your template explicitly. Here's an example:

{{ form.non_field_errors }} New password {{ form.password }}

Last updated on September 20th, 2009


#Django forms #CSRF protection #safe forms #Django #forms #protection #CSRF

Add your review!