Search code examples
djangodjango-formwizard

Validation based on previous step


Say I have an input on one step and another input on the next step (I am using SessionWizardView). I need to validate next step input is identical to input from previous step. It would be great to update validator on the go to show correct errors if inputs are not identical with input from previos step because I am using ajax validation that executes django form validators before submit.

I thought about getting session with ThreadLocal.get_current_request() in second step input validator and compare it somehow. But i dont think it is a good solution :) Any suggestions?


Solution

  • I think that should do it:

    class MyWizard(SessionWizardView):
        def get_form_kwargs(self, step):
            kwargs = {}
            if step == 'second_step':
                cleaned_data = self.get_cleaned_data_for_step('first_step')
                kwargs.update({'first_input': cleaned_data['first_input'] })
    
            return kwargs
    

    then you pop it in your second form

    class SecondForm(forms.Form):
        def __init__(self, *args, **kwargs):
            self.first_input = kwargs.pop('first_input', None)
            super(SecondForm, self).__init__(*args, **kwargs)
    
        def clean(self):
            super(SecondForm, self).clean()
            if any(self.errors):
                return
    
            # compare self.first_input with self.cleaned_data['second_input']
    
            return self.cleaned_data