检查一个字段是否小于另一个字段-表单,Django

我尝试检查开始时间是否小于结束时间。如果我不想引发错误。

我的代码如下所示:

class TimeOpeningHoursForm(forms.ModelForm):
    class Meta:
        model = BusinessOpeningHours
        fields = ('mon_st', 'mon_end', ...)
        widgets = {
            'mon_st': Select(attrs={'class': 'form-control'}),
            'mon_end': Select(attrs={'class': 'form-control'}),
            ...
        }

    def compare_mon(self):
        cleaned_data = self.cleaned_data
        st = cleaned_data['mon_st']
        end = cleaned_data['mon_end']
        if st > end :
             raise forms.ValidationError("The start time must be less than the end time.")
        else:
              return cleaned_data

My validation code works as if it wasn't there at all. Does not raise errors or verify correctness. In the view, of course, I check form via the is_valid method.

评论
抄凝雪
抄凝雪

Django will not automatically run this method. You can override the .clean() method [Django-doc] which is automatically called to validate fields that depend on each other:

class TimeOpeningHoursForm(forms.ModelForm):
    class Meta:
        model = BusinessOpeningHours
        fields = ('mon_st', 'mon_end')
        widgets = {
            'mon_st': Select(attrs={'class': 'form-control'}),
            'mon_end': Select(attrs={'class': 'form-control'})
        }

    def clean(self):
        cleaned_data = super().clean()
        st = cleaned_data['mon_st']
        end = cleaned_data['mon_end']
        if st > end :
             raise forms.ValidationError('The start time must be less than the end time.')
        return cleaned_data
点赞
评论