Django form validation: making “required” conditional?

后端 未结 2 972
礼貌的吻别
礼貌的吻别 2021-01-04 04:14

I\'m new to Django (and Python), and am trying to figure out how to conditionalize certain aspects of form validation. In this case, there\'s a HTML interface to the applica

2条回答
  •  滥情空心
    2021-01-04 04:34

    This is done with the clean method on the form. You need to set foo_date and foo_time to required=False, though, because clean is only called after every field has been validated (see also the documentation).

    class FooForm(forms.Form)
        # your field definitions
    
        def clean(self):
            data = self.cleaned_data
            if data.get('foo_timestamp', None) or (data.get('foo_date', None) and data.get('foo_time', None)):
                return data
            else:
                raise forms.ValidationError('Provide either a date and time or a timestamp')
    

提交回复
热议问题