django-safeform

CSRF protection for Django forms
Download

django-safeform Ranking & Summary

Advertisement

  • Rating:
  • License:
  • BSD License
  • Price:
  • FREE
  • Publisher Name:
  • Simon Willison
  • Publisher web site:
  • http://www.sslinks.co.uk

django-safeform Tags


django-safeform Description

CSRF protection for Django forms 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 "./manage.py runserver" in the examples folder to start a Django server demonstrating the functionality of the library. Use "./manage.py 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) @csrf_protect 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 }} Requirements: · Python · Django


django-safeform Related Software