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.

3 thoughts on “Trim Spaces in Django Forms”

  1. This code is also nice since if only whitespace is entered for a required field, the form will not accept it, which is what is expected most of the time.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s