Quite often I need to filter some form data before using it (saving to database etc.) Let\'s say I want to strip whitespaces and replace repeating whitespaces with a single
as i know Django don't have any native solutions to resolve you question. I can show only how i resolve this problem for myself. I advice you to use decorator for you ModelForm. Here the working code(also i use logging module):
#DECORATOR
def applyValidators(model_form):
def apply(*args,**kwargs):
try:
if hasattr(model_form.Meta.model,"validators"):
for field_name,fnc in model_form.Meta.model.validators.items():
setattr(model_form,"clean_%s" % field_name,fnc)
except Exception,err:
logging.error(str(err))
return model_form(*args,**kwargs)
return apply
#VALIDATORS
def validator(*args,**kwargs):
return "SOMEVALUE"
#MODEL
class MyModel(models.Model):
#Your fields
.......
.......
.......
#VALIDATE DICT
validators = {"username":validator,"email":validator}
#MODEL FORM
@applyValidators
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
.......
.......
.......