Search code examples
djangodjango-formsdjango-formwizard

Accessing variables in Django forms


The problem I've run into here is how to display some additional text in a form, specifically the values of the previous step. The point is to show the user a message such as "you have chosen {{ value_from_step_0 }} as your starter, now choose a main course."

I can get that value from step 0 as follows:

class MenuWizard(SessionWizardView):
    def get_form_kwargs(self, step=None):
        kwargs = {}
        if step == '1':
            starter = self.get_cleaned_data_for_step('0')['starter']
            kwargs.update({'starter': starter})

class MainCourseForm(forms.Form):
    def __init__(self, *args, **kwargs):
        starter = kwargs.pop('starter')
        print "{0} chosen".format(starter) # This works
        super(DomainForm, self).__init__(*args, **kwargs)
        # What next?

If I don't pop the 'starter' value then the super call fails. But, how may I get that value into the relevant template? Presumably I need to do something further within init or override something else, but what?


Solution

  • First, note that 1.7 is unsupported, and the form wizards were removed from Django in 1.8 and are now in the third-party formtools library.

    This isn't really a job for the form, but the view. SessionWizardView is a standard class-based view, and like most class-based views it allows you to override get_context_data to add elements to the template contents. See the documentation, which has an example of using self.steps.current to check the current step name.