Django 如何确保表单字段在有效时设置为required后仍为not required?

Django 如何确保表单字段在有效时设置为required后仍为not required?,django,django-forms,Django,Django Forms,我有一个表单,其中我将说明设置为非必需 class LeaveApprovalForm(forms.ModelForm): class Meta: model = LeaveRequest description = forms.CharField( widget=forms.Textarea, label='Reason', required=False ) def is_valid(self)

我有一个表单,其中我将
说明设置为非必需

class LeaveApprovalForm(forms.ModelForm):
    class Meta:
        model = LeaveRequest

    description = forms.CharField(
        widget=forms.Textarea,
        label='Reason',
        required=False
    )

    def is_valid(self):
        '''A description is not required when approving'''
        self.fields['description'].required = False
        if self.data.get('reject', None):
            self.fields['description'].required = True
        return super().is_valid()
但是,当表单验证并显示
时,此字段是必需的。
错误。html具有
required
属性,因此如果它未被拒绝和批准,则会触发需要数据输入的jquery弹出窗口


如何确保formis再次初始化时不需要它?

首先,您不应覆盖
是否有效。正确的重写方法称为
clean()

其次,不应修改字段的必需状态。相反,在
clean()
方法中,检查所需的组合,并在必要时提出验证错误

def clean(self):
    if self.data.get('reject') and not self.data.get('description'):
        raise forms.ValidationError('Description is required if data is supplied')
        # or
        self.add_error('description', '....')