Trim Spaces in Django Forms

Not sure if I agree with this ticket, but it appears Django won’t be adding support for removing leading / trailing whitespace from form fields. Other frameworks make this super easy. Hopefully the Django folks will put something together for 1.6+.

For now the best approach appears to be creating a base form class which all other forms subclass. The class looks like the following (thanks to Dave Dash and his library):

I have seen other posts recommending doing the work in the clean method but I find that this runs after any validation. So if you’re doing some regex validation that doesn’t allow leading / trailing spaces for instance, the validation will fail. It’s better to trim the whitespace first, then do the validation to avoid the user having to manually trim the spaces.

Django ModelForm, FormView and the Request Object

It’s often necessary to get access to the request object from within a ModelForm. To do this, you’ll need to override a single method in both the ModelForm and FormView.

First the FormView:

And now the ModelForm:

Django Class-based Forms

Diving into Django’s class-based forms and ran into a common problem with reverse(). As documented here the form takes three parameters – template name, form_class and success_url.

My first instinct was to do the following:

This blows up rather nicely. The solution is rather simple – reverse_lazy():

Override Django Form.is_valid()

For this project I won’t be using Django’s built-in user authentication application. It’s a bit restrictive for my taste (but getting better in Django 1.5 from what I can tell).

One common use case is to validate the user’s username and password when logging in. Rather than place this logic within the view, it’s cleaner to override the default is_valid method with some additional logic that checks the password.

Here’s an example form with a username and password field. The username field allows either a username or email address, and I’m using Django’s built-in password hasher.


You can then simply use form.is_valid() in your view: