Django Form Wizard with Conditional Questions

左心房为你撑大大i 提交于 2019-12-10 21:47:12

问题


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

回答1:


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.


来源:https://stackoverflow.com/questions/18164858/django-form-wizard-with-conditional-questions

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