在Django模型表格中有条件地只需要一个字段

时间:2010-01-28 02:52:50

标签: python django forms validation model

无论如何根据是否填写了同一表格中的另一个字段来有条件地建立一个字段?

If field1 has no data, but field2 does
    form is valid.

If field1 has no data and field2 has no data
    form is invalid

不寻找任何JavaScript解决方案。我认为它应该用django形式解决,但不太确定如何最好地解决它。

3 个答案:

答案 0 :(得分:9)

覆盖.clean(self)方法,检查self.cleaned_data并引发ValidationError

https://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other

答案 1 :(得分:6)

如果您知道验证将应用于此类的所有对象,您也可以使用该模型执行此操作。要在表单级别使用以下内容,请使用cleaning_data。以下是使用ValidationError的Django文档中的示例:

class Article(models.Model):

    status = models.CharField(max_length=75, blank=False, null=False)
    pub_date = models.CharField(max_length=75, blank=False, null=False)

    def clean(self):
        # Don't allow draft entries to have a pub_date.
        if self.status == 'draft' and self.pub_date is not None:
            raise ValidationError('Draft entries may not have a publication date.')
        # Set the pub_date for published items if it hasn't been set already.
        if self.status == 'published' and self.pub_date is None:
            self.pub_date = datetime.date.today()

参考:Model Instance CleanDjango Validators

以下是表单示例:

class SimpleForm(forms.ModelForm):

    def clean(self):
        cleaned_data = super(SimpleForm, self).clean()  # Get the cleaned data from default clean, returns cleaned_data
        field1 = cleaned_data.get("field1")
        field2 = cleaned_data.get("field2"),

        if not field1 and not field2:
            raise forms.ValidationError('Please fill in both fields.')

        return cleaned_data

参考:Form & Field Validation

答案 2 :(得分:0)

条件必需字段的最佳解决方案是覆盖表单的干净方法并在条件下弹出错误。例如:

clean(self):
    if self.cleaned_data.get(some_field) == 1:
        self.errors.pop(other_field, None)