clean() method in model and field validation

前端 未结 3 1892
挽巷
挽巷 2020-12-28 16:37

I have a problem with a model\'s clean() method and basic field validation. here\'s my model and the clean() method.

class Trial(mo         


        
3条回答
  •  温柔的废话
    2020-12-28 17:10

    I guess that's the way to go:

    class TrialForm(ModelForm):
    
        class Meta:
            model = Trial
    
        def clean(self):
    
            data = self.cleaned_data
            if not ('movement_start' in data.keys() and 'trial_start' in data.keys()  and 'trial_stop' in data.keys()):
                raise forms.ValidationError("Please fill out missing fields.")
    
            trial_start = data['trial_start']
            movement_start = data['movement_start']
            trial_stop = data['trial_stop']
    
            if not (movement_start >= trial_start):
                raise forms.ValidationError('movement start must be >= trial start')
    
            if not (trial_stop >= movement_start):
                raise forms.ValidationError('trial stop must be >= movement start')
    
            if not (trial_stop > trial_start):
                raise forms.ValidationError('trial stop must be > trial start')
    
            return data
    

    EDIT the downside of this approach is, that value checking will only work if I create objects through the form. Objects that are created on the python shell won't be checked.

提交回复
热议问题