Django将自定义验证添加到表单中的选择字段

时间:2019-03-18 10:49:33

标签: python django django-models django-forms

我有一个模型表格,

models.py
Y_N = (('Y', 'Yes'), ('N', 'No'))
M_A = (('M', 'Man'), ('A', 'Auto'))

class Test(models.Model):
    feild1 = models.CharField(max_length=1, choices=Y_N, default='Y', db_index=True)
    feild2 = models.CharField(max_length = 1, choice=M_A, default = 'M')
表格
class TestForm(ModelForm):
    class Meta:
        model = Test
        feilds = ['feild1', 'feild2']

现在在模板中,我添加了另一个选择值为“不更新”,其值为0。那么我该如何处理此'Select a valid choice. 0 is not one of the available choices.'。如果字段值为0或'Y'或'N',则我需要提交该表单。

2 个答案:

答案 0 :(得分:0)

您将(0, "Don't update")添加到Y_N,因此这是一个有效的选择。

答案 1 :(得分:0)

您需要在Form中执行此操作。例如,您可以覆盖clean方法,或者在这种情况下,仅覆盖特定的clean_FOO方法:

class TestForm(ModelForm):

    class Meta:
        ... # same as before

    def clean(self):
        cleaned_data = super().clean()
        if self.errors.get('field1') and self.data.get('field1') == '0':
            # we know the error is because submitted data doesn't match model options
            del self._errors['field1']  # error on field1 removed
        return cleaned_data  # note cleaned_data won't contain 'field1' so it won't save it.