I am looking for the best solution of this task. I have simple class of form in 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
This is only some draft.
The behavior of form should be following: When I will choose C1 category from radio select fields, subcategory_c1 should be required. When I will choose C2 category, subcategory_c2 should be required and select other subcategories fields (C1,C3,C4) should be optional. I hope my explanation is clear.
Draft of form in template:
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>>
Thanks for help in advance.
Your solution requires a lot of things to do in case if new choices added.
Cleaner way is to make
subcategoryone field with all possible choices and filter them with JavaScript on client side. As a fallback for users without js there should be all possible well-categorized choices.This solution makes sense since you need field with dynamically changing choices – looks like work for client-side magic. 🙂