Skip to content

Instantly share code, notes, and snippets.

@victorono
Created May 28, 2014 16:13
Show Gist options
  • Select an option

  • Save victorono/2dfb5c7d40a1e9538f06 to your computer and use it in GitHub Desktop.

Select an option

Save victorono/2dfb5c7d40a1e9538f06 to your computer and use it in GitHub Desktop.
Strip all blank spaces in inputs
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django import forms
from django.forms.fields import FileField
from django.core.exceptions import ValidationError
class BaseForm:
def _clean_fields(self):
for name, field in self.fields.items():
value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))
try:
if isinstance(field, FileField):
initial = self.initial.get(name, field.initial)
value = field.clean(value, initial)
else:
if isinstance(value, basestring):
value = field.clean(value.strip())
else:
value = field.clean(value)
self.cleaned_data[name] = value
if hasattr(self, 'clean_%s' % name):
value = getattr(self, 'clean_%s' % name)()
self.cleaned_data[name] = value
except ValidationError, e:
self._errors[name] = self.error_class(e.messages)
if name in self.cleaned_data:
del self.cleaned_data[name]
class Form(BaseForm, forms.Form):
pass
class ModelForm(BaseForm, forms.ModelForm):
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment