Question

I've been struggling with this problem and can't seem to find a solution...

I have a FormWizard which contains two steps: a Form (step0), then a FormSet (step1):

forms.py

# Step 0
class StrategyForm(forms.ModelForm):
     class Meta:
        model = Strategy

# Step 1
class LegForm(forms.ModelForm):
    class Meta:
        model = Leg

LegFormSet = formset_factory(LegForm, max_num=10)

In step0, the user enters a number, which I would like to use in the FormSet as the "extra", i.e. if the user inputs 10 in step0, I would like the FormSet to appear with 10 Forms in the next step.

I have tried the following based on other questions, but can't seem to find a solution:

views.py

def get_form(self, step=None, data=None, files=None):
    if step is None:
        step = self.steps.current

    form = super(DealWizard, self).get_form(step, data, files)

    if step == 'leg':
        form.extra = 10
    return form

and

def get_form(self, step=None, data=None, files=None):
    if step is None:
        step = self.steps.current

    form = super(DealWizard, self).get_form(step, data, files)

    if step == 'leg':
        mgmt_form = form.management_form
        mgmt_form.initial[INITIAL_FORM_COUNT] = 10
        mgmt_form.initial[TOTAL_FORM_COUNT] = 10

    return form

I'm (very) new to django, so any advice will help :)

Was it helpful?

Solution

Try this:

def get_form(self, step=None, data=None, files=None):
    if step is None:
        step = self.steps.current
    if step == "1": 
        prev_data = self.get_cleaned_data_for_step(self.get_prev_step(
                                                     self.steps.current))
        cnt = prev_data['extra_from_step0'] #use appropriate key as per your form

        return formset_factory(LegForm, extra=cnt, max_num=cnt) 

    return super(YourFormWizard, self).get_form(step, data, files)

It overrides get_form() method to get count from previous step and return formset_factory() with those many forms using max_num.

As side node, you may want to use modelformset_factory().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top