Using Django FormWizard in a view

I recently needed to use a Django form wizard from a view. I needed it in a view as I had some permissions that I needed to check and also wanted to supply some initial data as the form would now be editing information that was previously supplied.

I had found some code on Django Snippets but it was also messing around with the way that form wizards were defined. I didn’t want to change the way that form wizards behaved so I stripped out the changes and was left with a minimal way to use a form wizard in a view.

The main thing to notice is that first you have to create an instance of the FormWizard. Then as the object to return from the view you must call the instance passing through the context and the request.

Example:


@login_required
def edit_form_wizard(request, slug):
    # Do some permission checking
    ..... snip .....

    # Set up the dictionary of initial data for the form
    # In this case, we are pre-filling some data from the first form only
    initial = {0: {'first_name': request.user.first_name,
                   'last_name': request.user.last_name,
                   'email': request.user.email,
                  },
              }

    # Create the form wizard
    form = EditFormWizard([ContactForm, SecondForm, ThirdForm], initial=initial)

    # Call the form wizard passing through the context and the request
    return form(context=RequestContext(request), request=request)

About Anthony Batchelor

Job: Software engineer at Mercurytide Hobbies: Guitar/Band, Kendo, Beer Brewing, Simple Electronics, Python hacking.
This entry was posted in Django, Programming, Web and tagged , , . Bookmark the permalink.

One Response to Using Django FormWizard in a view

  1. This was a huge help! I’d been looking for a way to protect my form wizard in a @login_required, but didn’t know I had to pass context and request into it as input.

    Thanks so much for this post.

    Michael

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>