Django FormWizards: How to painlessly pass user-entered data between forms?

梦想与她 提交于 2019-12-03 21:47:31

问题


I'm using the FormWizard functionality in Django 1.4.3.

I have successfully created a 4-step form. In the first 3 steps of the form it correctly takes information from the user, validates it, etc. In Step #4, it right now just shows a "Confirm" button. Nothing else. When you hit "Confirm" on step #4, does something useful with it in the done() function. So far it all works fine.

However, I would like to make it so that in step 4 (The confirmation step), it shows the user the data they have entered in the previous steps for their review. I'm trying to figure out the most painless way to make this happen. So far I am creating an entry in the context called formList which contains a list of forms that have already been completed.

class my4StepWizard(SessionWizardView):

    def get_template_names(self):
        return [myWizardTemplates[self.steps.current]]

    def get_context_data(self, form, **kwargs):
        context = super(my4StepWizard, self).get_context_data(form=form, **kwargs)
        formList = [self.get_form_list()[i[0]] for i in myWizardForms[:self.steps.step0]]

        context.update(
            {
                'formList': formList,
            }
        )
        return context        


    def done(self, form_list, **kwargs):
        # Do something here.
        return HttpResponseRedirect('/doneWizard')

Form #1 has an input field called myField. So in my template for step #4, I would like to do {{ formList.1.clean_myField }}. However, when I do that, I get the following error:

Exception Value:
'my4StepWizard' object has no attribute 'cleaned_data'

It seems that the forms I am putting into formList are unbounded. So they don't contain the user's data. Is there a fix I can use to get the data itself? I would really like to use the context to pass the data as I'm doing above.


回答1:


Try this:

def get_context_data(self, form, **kwargs):
    previous_data = {}
    current_step = self.steps.current # 0 for first form, 1 for the second form..

    if current_step == '3': # assuming no step is skipped, this will be the last form
        for count in range(3):
            previous_data[unicode(count)] = self.get_cleaned_data_for_step(unicode(count))

    context = super(my4StepWizard, self).get_context_data(form=form, **kwargs)
    context.update({'previous_cleaned_data':previous_data})
    return context

previous_data is a dictionary and its keys are the steps for the wizard (0 indexed). The item for each key is the cleaned_data for the form in the step which is the same as the key.



来源:https://stackoverflow.com/questions/14860392/django-formwizards-how-to-painlessly-pass-user-entered-data-between-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!