基于以前的FormWizard步骤将表单添加到Formset

时间:2014-03-25 12:12:39

标签: python django formset

我一直在努力解决这个问题,似乎无法找到解决方案......

我有一个FormWizard,它包含两个步骤:一个Form(step0),然后一个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)

在步骤0中,用户输入一个数字,我想在FormSet中使用它作为“额外”,即如果用户在步骤0中输入10,我希望FormSet在下一步中显示10个表单

我根据其他问题尝试了以下内容,但似乎无法找到解决方案:

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

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

我是(非常)django的新手,所以任何建议都会有所帮助:)

1 个答案:

答案 0 :(得分:0)

试试这个:

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)

它会覆盖get_form()方法以从上一步骤中获取计数,并使用formset_factory()返回max_num多个表单。

作为辅助节点,您可能希望使用modelformset_factory()