Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create Dependent dropdown in Django forms?

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.

like image 893
Viraj Avatar asked Apr 20 '26 21:04

Viraj


1 Answers

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,
        )
    )
like image 85
Jieter Avatar answered Apr 22 '26 10:04

Jieter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!