我正在寻找这项任务的最佳解决方案。我在 forms.py 中有简单的表单类:
class CategoriesForm(Form):
RADIO_CHOICES = (
('c1', _("C1")),
('c2', _("C2")),
('c3', _("C3")),
('c4', _("C4")),
)
category = forms.ChoiceField(widget=forms.RadioSelect(),choices=RADIO_CHOICES)
subcategory_c1 = forms.ModelChoiceField(queryset=Category.objects.filter(type="c1", public=True), empty_label="", label = "hhh")
subcategory_c2 = forms.ModelChoiceField(queryset=Category.objects.filter(type="c2", public=True), empty_label="", label = "rrr")
subcategory_c3 = forms.ModelChoiceField(queryset=Category.objects.filter(type="c3", public=True), empty_label="", label = "aaa")
subcategory_c4 = forms.ModelChoiceField(queryset=Category.objects.filter(type="c4", public=True), empty_label="", label = "eeee")
def __init__(self, *args, **kwargs):
super(CategoriesForm, self).__init__(*args, **kwargs)
self.fields["subcategory_c1"].required = False
self.fields["subcategory_c2"].required = False
self.fields["subcategory_c3"].required = False
self.fields["subcategory_c4"].required = False
这只是一些草稿。
表单的行为应该如下:当我从单选字段中选择 C1 类别时,应该需要 subcategory_c1。当我选择 C2 类别时,subcategory_c2 应该是必需的,而选择其他子类别字段(C1、C3、C4)应该是可选的。我希望我的解释清楚。
模板中的表格草稿:
field category (RadioSelect: C1, C2, C3, C4) <<required>>
field subcategory_c1 (Select: ---, a,b,c,d) <<required only if user checked C1>>
field subcategory_c2 (Select: ---, a,b,c,d) <<required only if user checked C2>>
field subcategory_c3 (Select: ---, a,b,c,d) <<required only if user checked C3>>
field subcategory_c4 (Select: ---, a,b,c,d) <<required only if user checked C4>>
提前感谢您的帮助。