带条件问题的Django表单向导 [英] Django Form Wizard with Conditional Questions
问题描述
在我的Django应用程序中,我目前有一个带有几个表单类的表单向导.我希望有条件的问题.这意味着,如果用户为某个问题选择是",则表单中的另一个问题将变为必需,而javascript将使该问题可见.我找到了一个如何在线执行此操作的示例,但是它不起作用.关于如何创建此功能的任何建议?
In my Django application, I currently have a form wizard with a few form classes. I would like to have the ability to have conditional questions. Meaning if the user selects yes for a certain question, another question within the form will become required and javascript will make the question visible. I found an example of how to do this online, however it doesn't work. Any suggestions on how I can create this functionality?
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
推荐答案
尝试将表单的__init__
方法替换为自定义的clean_are_you_cool
方法.因此,如果用户提交值Yes
,则应检查是否也填充了how_cool
字段.您还应该在客户端执行此操作,以提供出色的用户体验.这样的形式:
Try to replace __init__
method of your form with custom clean_are_you_cool
method. So, if user submit value Yes
you should check if how_cool
field is populated too. You also should do this on client side to provide great user experience. Something like this with forms:
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.
这篇关于带条件问题的Django表单向导的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!