如何在2组合框Django窗体中显示不重复的值

2024-10-03 19:20:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个django形式的组合框,它们都显示来自db的相同资源。示例:我在db include value中有一个表Country:'USA'、'Japan'、'England'。现在我有两个combobox2从表Country获取数据来显示值,如果在combobox1(from\ u Country)中我选择了'USA',那么combobox2(to\ u Country)只显示了'Japan'和'England',不再显示'USA'。我该怎么做?这是我的表单.py文件

class MyModelChoiceField(ModelChoiceField):
def label_from_instance(self, obj):
    return obj.name

class MyForm(forms.ModelForm):
from_country = MyModelChoiceField(queryset=None, empty_label='---Select---',
                                   widget=forms.Select(attrs={'class': 'form-control'}),
                                   error_messages={'required': 'This field is required.'})
to_country = MyModelChoiceField(queryset=None, empty_label='---Select---',
                                 widget=forms.Select(attrs={'class': 'form-control'}),
                                 error_messages={'required': 'This field is required.'})
def __init__(self, *args, **kwargs):
    super(ExchangeRateForm, self).__init__(*args, **kwargs)
    self.fields['from_country'].queryset = Country.objects.filter(is_hidden=0)
    self.fields['to_country'].queryset = Country.objects.filter(is_hidden=0)

Tags: tofromselfdbisrequiredformsselect