Automatically strip whitespace in Django forms
12 October 2009
The current project I'm working has at the time of writing 20 different forms (90% model forms) instantiated in different scenarios. Django doesn't automatically strip whitespace in text based fields. So instead of doing this:
class ContactMarketingForm(forms.ModelForm): class Meta: model = ContactMarketing exclude = ('contact',) def clean_notes(self): return self.cleaned_data['notes'].strip() def clean_name(self): return self.cleaned_data['name'].strip()
Instead I wrote a common class for all of my form classes to use:
class _BaseForm(object): def clean(self): for field in self.cleaned_data: if isinstance(self.cleaned_data[field], basestring): self.cleaned_data[field] = self.cleaned_data[field].strip() return self.cleaned_data class BaseModelForm(_BaseForm, forms.ModelForm): pass class ContactMarketingForm(BaseModelForm): class Meta: model = ContactMarketing exclude = ('contact',)
Now all text inputs and textareas are automatically whitespace stripped. Perhaps useful for other Djangonauts.