[英]Django Form Wizard with Conditional Questions
在我的Django應用程序中,我目前有一個帶有幾個表單類的表單向導。 我希望能夠有條件問題。 意思是如果用戶為某個問題選擇“是”,則表單中的另一個問題將變為必需,並且javascript將使問題可見。 我找到了一個如何在線完成此操作的示例,但它不起作用。 有關如何創建此功能的任何建議?
class QuestionForm(forms.Form):
COOL_LIST = (
('cool','Cool'),
('really cool','Really Cool'),
)
YES, NO = 'yes','no'
YES_NO = (
(YES,'Yes'),
(NO,'No'),
)
are_you_cool = forms.ChoiceField(choices=YES_NO,label='Are you cool?')
how_cool = forms.MultipleChoiceField(required=False,widget=CheckboxSelectMultiple, choices=COOL_LIST,label='How cool are you?')
def __init__(self, data=None, *args, **kwargs):
super(QuestionForm, self).__init__(data, *args, **kwargs)
if data and data.get('are_you_cool', None) == self.YES:
self.fields['how_cool'].required = True
嘗試使用自定義clean_are_you_cool
方法替換表單的__init__
方法。 因此,如果用戶提交值為Yes
,則應檢查是否也填充了how_cool
字段。 您還應該在客戶端執行此操作以提供出色的用戶體驗。 形式有這樣的東西:
def clean_are_you_cool(self):
if self.cleaned_data.get('are_you_cool', None) == 'Yes':
if self.cleaned_data.get('how_cool', None) is not None:
# Actions for cool user.
pass
# Or if user not cool.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.