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.
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.
Will the same code work for a ModelForm?
ie just switching class BaseForm(Form) to BaseModelForm(ModelForm)?
Yes, it sure will.