How to create Dependent dropdown in Django forms?

爱⌒轻易说出口 提交于 2019-12-08 11:33:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!