Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django formwizard: passing data between forms

Tags:

python

django

I have a form wizard that contains 3 forms. Basically, what I am trying to do is to pass data from first and second forms to the third one. What I tried is to add a dictionary attribute to wizard class and update that dictionary every time the method process_step is called. Django 1.4 documentation says that this method is called every time a page is rendered for all submitted steps.

In the following sample code, dictionary attribute is changed with integer self.test to keep it simple. In this case, every time the method process_step is called, the value of self.test is 2, never increases. It seems that the method __init__ is called for each form.

class MyWizard(SessionWizardView):
    def __init__(self, *args, **kwargs):
        super(MyWizard, self).__init__(*args, **kwargs)
        self.test = 1

    def process_step(self, form):
        self.test += 1  
        print self.test
        return self.get_form_step_data(form)

Other than this solution, is there a more elegant way to pass data between forms of form wizard?

like image 295
sefakilic Avatar asked Dec 21 '22 20:12

sefakilic


2 Answers

What I would do is the following:

class MyWizard(SessionWizardView):
    def get_context_data(self, form, **kwargs):
        context = super(MyWizard, self).get_context_data(form=form, **kwargs)
        if self.steps.step1 == 3:
            data_from_step_1 = self.get_cleaned_data_for_step('0') # zero indexed
            data_from_step_2 = self.get_cleaned_data_for_step('1') # zero indexed
            context.update({'data_from_step_1':data_from_step_1,
                            'data_from_step_2':data_from_step_2})
        return context
like image 79
spyrosikmd Avatar answered Jan 02 '23 05:01

spyrosikmd


I have little experience with formwizard but from django docs this looks like what you're after.

def get_context_data(self, form, **kwargs):
    context = super(MyWizard, self).get_context_data(form=form, **kwargs)
    if self.steps.current == 'my_step_name':
        context.update({'another_var': True})
    return context
like image 36
slackjake Avatar answered Jan 02 '23 06:01

slackjake