Django形式:我如何填写一个字段但不可能填写两个字段?

时间:2015-05-25 00:20:56

标签: python django django-forms

我希望有一个选项可以链接到文件或上传文件。显然你不能做到这两点。我该如何实现呢?

1 个答案:

答案 0 :(得分:0)

Take a look at the Django docs about the clean function for cleaning and validating fields that depend on each other.

然后,您可以在clean内检查两个字段的值。

这些方面的东西:

from django import forms
from django.core.exceptions import ValidationError


class MyForm(forms.Form):

    field_1 = forms.CharField(required=False)

    field_2 = forms.CharField(required=False)

    def clean(self):

        # Get the field values submitted
        cleaned_data = super(MyForm, self).clean()
        field_1_data = cleaned_data.get('field_1')
        field_2_data = cleaned_data.get('field_2')

        # Check that only one field is filled out.
        if field_1_data and field_2_data:
            raise ValidationError('Only fill out one field please.', code='invalid')