Django 表单:如何使必须填写一个字段但不能同时填写两个字段?

Django forms: How do I make it necessary to fill out one field but not possible to fill out both?

我想要link 到文件或上传文件的选项。显然你不能两者都做。我该如何实施?

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')