简体   繁体   English

带有条件问题的Django表单向导

[英]Django Form Wizard with Conditional Questions

In my Django application, I currently have a form wizard with a few form classes. 在我的Django应用程序中,我目前有一个带有几个表单类的表单向导。 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. 意思是如果用户为某个问题选择“是”,则表单中的另一个问题将变为必需,并且javascript将使问题可见。 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

Try to replace __init__ method of your form with custom clean_are_you_cool method. 尝试使用自定义clean_are_you_cool方法替换表单的__init__方法。 So, if user submit value Yes you should check if how_cool field is populated too. 因此,如果用户提交值为Yes ,则应检查是否也填充了how_cool字段。 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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM