问题
I want to create dependent dropdowns. For example, if someone selects book from the first dropdown, second dropdown should have chapter listed under that book. I have achieved it using HTML / Jquery / AJAX. But i am now interested to achieve same using Django forms. If anyone have idea, please share it.
Thank you in advance.
回答1:
If you are not afraid of adding dependencies: django-select2 has an implementation of chained selects, which can be configured using the django form API. Example from their docs:
class AddressForm(forms.Form):
country = forms.ModelChoiceField(
queryset=Country.objects.all(),
label=u"Country",
widget=ModelSelect2Widget(
model=Country,
search_fields=['name__icontains'],
)
)
city = forms.ModelChoiceField(
queryset=City.objects.all(),
label=u"City",
widget=ModelSelect2Widget(
model=City,
search_fields=['name__icontains'],
dependent_fields={'country': 'country'},
max_results=500,
)
)
来源:https://stackoverflow.com/questions/48147631/how-to-create-dependent-dropdown-in-django-forms