Django: how to cleanup form fields and avoid code duplication

前端 未结 1 1724
情深已故
情深已故 2021-01-13 19:57

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

1条回答
  •  一生所求
    2021-01-13 20:06

    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
        .......
        .......
        .......
    

    0 讨论(0)
提交回复
热议问题