My approach is borrowed from here . But instead of subclassing django.forms.Form, I use mixin. That way I can use it with both Form and ModelForm . The method defined here overrides the BaseForm _clean_fields method.
class StripWhitespaceMixin(object): def _clean_fields(self): for name, field in self.fields.items():
To use, just add mixin to your form
class MyForm(StripeWhitespaceMixin, ModelForm): ...
Alternatively, if you want to trim whitespace while saving models that don't have a form, you can use the following mixin. By default, models without forms are not checked. I use this when I create objects based on json data returned from an external api rest call.
class ValidateModelMixin(object): def clean(self): for field in self._meta.fields: value = getattr(self, field.name) if value:
Then in your models.py file
class MyModel(ValidateModelMixin, Model): ....
pymarco
source share