问题
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