How to create 'child' questions in Django forms?

给你一囗甜甜゛ 提交于 2019-12-25 02:37:12

问题


I would like to know how to create 'child' questions using Django forms. Thats is, questions which are only visible depending on the answer provided in a preceding question.

I'm fairly sure I'm not using the correct terminology with the term 'child' questions but I am sure someone will figure out what I mean

In the below example, when the user selects "United States of America" The option to select which state they are from should become visible. This would be standard on my website forms.

Is there a standard functionality available to do this?

Country List

   COUNTRY = (   
        ("", "----------"), 
        (AFGHANISTAN, 'Afghanistan'),
        (ALBANIA, 'Albania'),
        ....
        (UNITED STATES OF AMERICA, 'United States of America'),
        ....
        (ZAMBIA, 'Zambia'),
        (ZIMBABWE, 'Zimbabwe'),

        COUNTRY = forms.ChoiceField(widget=forms.Select(), choices=COUNTRY, initial="", label='What Country are you from?')

State list

STATE = (
        ("", "----------"), 
        (ALABAMA, 'Alabama'),
        (ALASKA, 'Alaska'),
        (ARIZONA, 'Arizona'),
        ....
        ....
        (WYOMING, 'Wyoming'),
        (DISTRICT_OF_COLUMBIA, 'District of Columbia'),
        (PUERTO_RICO, 'Puerto Rico'),
        (GUAM, 'Guam'),
        (AMERICAN_SAMOA, 'American Samoa'),
        (US_VIRGIN_ISLANDS, 'US Virgin Islands'),
        (NORTHERN_MARIANO_ISLANDS, 'Northern Mariana Islands'),
            )

    state = forms.ChoiceField(widget=forms.Select(), choices=STATE, initial="", label='What State are you from?')

回答1:


You should probably just use javascript to show/hide the "child" selector, and then when you process your form, only save a state value if the country value is USA.



来源:https://stackoverflow.com/questions/25918951/how-to-create-child-questions-in-django-forms

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