Search code examples
djangodjango-formsdjango-formwizard

Dynamically populate ChoiceField Formset in Formwizard


I'm trying to populate a ChoiceField in a FormSet with info from a previous step (a bit relevant to my last asked question). I'm almost there, but can't seem to initialize the list:

def get_form(self, step=None, data=None, files=None):

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

        step = step or self.steps.current

        if step == 'pages':
            form_class = self.form_list[step]
            form1_cleaned_data = self.get_cleaned_data_for_step('agenda')
            formset = PagesFormSet()

            loan_choices = []


            for form in formset.forms:
                if form1_cleaned_data:
                    form.fields['agenda_select'].choices = [item for item in form1_cleaned_data.items()]

            # print(form.fields['agenda_select'])

            return PagesFormSet(data = data)

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

The list just doesn't show. However, printing in the console does work. If I just return formset instead of PagesFormSet, the list does populate. However, the list is then not valid and I can't continue to the next step (also the case if I add data = data then. I think I should add some extra info to the return PagesFormSet(data = data), but I just don't have a clue.

I would love some help as I have been staring for a day at this problem. Many thanks!


Solution

  • I found the answer! What I did was return the formset instead of the PagesFormSet. However, I already gave the PagesFormset when initiating formset the required data. This apparently means that the formset contains both the data as well as the extra info from the choices. For future reference:

    def get_form(self, step=None, data=None, files=None):
    
            form = super(FormWizardView, self).get_form(step, data, files)
    
            step = step or self.steps.current
    
            if step == 'pages':
                form_class = self.form_list[step]
                form1_cleaned_data = self.get_cleaned_data_for_step('agenda')
                formset = PagesFormSet(data = data)
    
                loan_choices = []
    
    
                for form in formset.forms:
                    if form1_cleaned_data:
                        form.fields['agenda_select'].choices = [item for item in form1_cleaned_data.items()]
    
                # print(form.fields['agenda_select'])
    
                return formset
    
            return super(FormWizardView, self).get_form(step, data, files)