form_wizard.txt 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. ===========
  2. Form wizard
  3. ===========
  4. **New in Django development version.**
  5. Django comes with an optional "form wizard" application that splits forms_
  6. across multiple Web pages. It maintains state in hashed HTML
  7. ``<input type="hidden">`` fields, and the data isn't processed server-side
  8. until the final form is submitted.
  9. You might want to use this if you have a lengthy form that would be too
  10. unwieldy for display on a single page. The first page might ask the user for
  11. core information, the second page might ask for less important information,
  12. etc.
  13. The term "wizard," in this context, is `explained on Wikipedia`_.
  14. .. _explained on Wikipedia: http://en.wikipedia.org/wiki/Wizard_%28software%29
  15. .. _forms: ../forms/
  16. How it works
  17. ============
  18. Here's the basic workflow for how a user would use a wizard:
  19. 1. The user visits the first page of the wizard, fills in the form and
  20. submits it.
  21. 2. The server validates the data. If it's invalid, the form is displayed
  22. again, with error messages. If it's valid, the server calculates a
  23. secure hash of the data and presents the user with the next form,
  24. saving the validated data and hash in ``<input type="hidden">`` fields.
  25. 3. Step 1 and 2 repeat, for every subsequent form in the wizard.
  26. 4. Once the user has submitted all the forms and all the data has been
  27. validated, the wizard processes the data -- saving it to the database,
  28. sending an e-mail, or whatever the application needs to do.
  29. Usage
  30. =====
  31. This application handles as much machinery for you as possible. Generally, you
  32. just have to do these things:
  33. 1. Define a number of ``django.forms`` ``Form`` classes -- one per wizard
  34. page.
  35. 2. Create a ``FormWizard`` class that specifies what to do once all of your
  36. forms have been submitted and validated. This also lets you override some
  37. of the wizard's behavior.
  38. 3. Create some templates that render the forms. You can define a single,
  39. generic template to handle every one of the forms, or you can define a
  40. specific template for each form.
  41. 4. Point your URLconf at your ``FormWizard`` class.
  42. Defining ``Form`` classes
  43. =========================
  44. The first step in creating a form wizard is to create the ``Form`` classes.
  45. These should be standard ``django.forms`` ``Form`` classes, covered in the
  46. `forms documentation`_.
  47. These classes can live anywhere in your codebase, but convention is to put them
  48. in a file called ``forms.py`` in your application.
  49. For example, let's write a "contact form" wizard, where the first page's form
  50. collects the sender's e-mail address and subject, and the second page collects
  51. the message itself. Here's what the ``forms.py`` might look like::
  52. from django import forms
  53. class ContactForm1(forms.Form):
  54. subject = forms.CharField(max_length=100)
  55. sender = forms.EmailField()
  56. class ContactForm2(forms.Form):
  57. message = forms.CharField(widget=forms.Textarea)
  58. **Important limitation:** Because the wizard uses HTML hidden fields to store
  59. data between pages, you may not include a ``FileField`` in any form except the
  60. last one.
  61. .. _forms documentation: ../forms/
  62. Creating a ``FormWizard`` class
  63. ===============================
  64. The next step is to create a ``FormWizard`` class, which should be a subclass
  65. of ``django.contrib.formtools.wizard.FormWizard``.
  66. As your ``Form`` classes, this ``FormWizard`` class can live anywhere in your
  67. codebase, but convention is to put it in ``forms.py``.
  68. The only requirement on this subclass is that it implement a ``done()`` method,
  69. which specifies what should happen when the data for *every* form is submitted
  70. and validated. This method is passed two arguments:
  71. * ``request`` -- an HttpRequest_ object
  72. * ``form_list`` -- a list of ``django.forms`` ``Form`` classes
  73. In this simplistic example, rather than perform any database operation, the
  74. method simply renders a template of the validated data::
  75. from django.shortcuts import render_to_response
  76. from django.contrib.formtools.wizard import FormWizard
  77. class ContactWizard(FormWizard):
  78. def done(self, request, form_list):
  79. return render_to_response('done.html', {
  80. 'form_data': [form.cleaned_data for form in form_list],
  81. })
  82. Note that this method will be called via ``POST``, so it really ought to be a
  83. good Web citizen and redirect after processing the data. Here's another
  84. example::
  85. from django.http import HttpResponseRedirect
  86. from django.contrib.formtools.wizard import FormWizard
  87. class ContactWizard(FormWizard):
  88. def done(self, request, form_list):
  89. do_something_with_the_form_data(form_list)
  90. return HttpResponseRedirect('/page-to-redirect-to-when-done/')
  91. See the section "Advanced ``FormWizard`` methods" below to learn about more
  92. ``FormWizard`` hooks.
  93. .. _HttpRequest: request_response/#httprequest-objects
  94. Creating templates for the forms
  95. ================================
  96. Next, you'll need to create a template that renders the wizard's forms. By
  97. default, every form uses a template called ``forms/wizard.html``. (You can
  98. change this template name by overriding ``FormWizard.get_template()``, which is
  99. documented below. This hook also allows you to use a different template for
  100. each form.)
  101. This template expects the following context:
  102. * ``step_field`` -- The name of the hidden field containing the step.
  103. * ``step0`` -- The current step (zero-based).
  104. * ``step`` -- The current step (one-based).
  105. * ``step_count`` -- The total number of steps.
  106. * ``form`` -- The ``Form`` instance for the current step (either empty or
  107. with errors).
  108. * ``previous_fields`` -- A string representing every previous data field,
  109. plus hashes for completed forms, all in the form of hidden fields. Note
  110. that you'll need to run this through the ``safe`` template filter, to
  111. prevent auto-escaping, because it's raw HTML.
  112. It will also be passed any objects in ``extra_context``, which is a dictionary
  113. you can specify that contains extra values to add to the context. You can
  114. specify it in two ways:
  115. * Set the ``extra_context`` attribute on your ``FormWizard`` subclass to a
  116. dictionary.
  117. * Pass ``extra_context`` as extra parameters in the URLconf.
  118. Here's a full example template::
  119. {% extends "base.html" %}
  120. {% block content %}
  121. <p>Step {{ step }} of {{ step_count }}</p>
  122. <form action="." method="post">
  123. <table>
  124. {{ form }}
  125. </table>
  126. <input type="hidden" name="{{ step_field }}" value="{{ step0 }}" />
  127. {{ previous_fields|safe }}
  128. <input type="submit">
  129. </form>
  130. {% endblock %}
  131. Note that ``previous_fields``, ``step_field`` and ``step0`` are all required
  132. for the wizard to work properly.
  133. Hooking the wizard into a URLconf
  134. =================================
  135. Finally, give your new ``FormWizard`` object a URL in ``urls.py``. The wizard
  136. takes a list of your form objects as arguments::
  137. from django.conf.urls.defaults import *
  138. from mysite.testapp.forms import ContactForm1, ContactForm2, ContactWizard
  139. urlpatterns = patterns('',
  140. (r'^contact/$', ContactWizard([ContactForm1, ContactForm2])),
  141. )
  142. Advanced ``FormWizard`` methods
  143. ===============================
  144. Aside from the ``done()`` method, ``FormWizard`` offers a few advanced method
  145. hooks that let you customize how your wizard works.
  146. Some of these methods take an argument ``step``, which is a zero-based counter
  147. representing the current step of the wizard. (E.g., the first form is ``0`` and
  148. the second form is ``1``.)
  149. ``prefix_for_step``
  150. ~~~~~~~~~~~~~~~~~~~
  151. Given the step, returns a ``Form`` prefix to use. By default, this simply uses
  152. the step itself. For more, see the `form prefix documentation`_.
  153. Default implementation::
  154. def prefix_for_step(self, step):
  155. return str(step)
  156. .. _form prefix documentation: ../forms/#prefixes-for-forms
  157. ``render_hash_failure``
  158. ~~~~~~~~~~~~~~~~~~~~~~~
  159. Renders a template if the hash check fails. It's rare that you'd need to
  160. override this.
  161. Default implementation::
  162. def render_hash_failure(self, request, step):
  163. return self.render(self.get_form(step), request, step,
  164. context={'wizard_error': 'We apologize, but your form has expired. Please continue filling out the form from this page.'})
  165. ``security_hash``
  166. ~~~~~~~~~~~~~~~~~
  167. Calculates the security hash for the given request object and ``Form`` instance.
  168. By default, this uses an MD5 hash of the form data and your
  169. `SECRET_KEY setting`_. It's rare that somebody would need to override this.
  170. Example::
  171. def security_hash(self, request, form):
  172. return my_hash_function(request, form)
  173. .. _SECRET_KEY setting: ../settings/#secret-key
  174. ``parse_params``
  175. ~~~~~~~~~~~~~~~~
  176. A hook for saving state from the request object and ``args`` / ``kwargs`` that
  177. were captured from the URL by your URLconf.
  178. By default, this does nothing.
  179. Example::
  180. def parse_params(self, request, *args, **kwargs):
  181. self.my_state = args[0]
  182. ``get_template``
  183. ~~~~~~~~~~~~~~~~
  184. Returns the name of the template that should be used for the given step.
  185. By default, this returns ``'forms/wizard.html'``, regardless of step.
  186. Example::
  187. def get_template(self, step):
  188. return 'myapp/wizard_%s.html' % step
  189. If ``get_template`` returns a list of strings, then the wizard will use the
  190. template system's ``select_template()`` function, `explained in the template docs`_.
  191. This means the system will use the first template that exists on the filesystem.
  192. For example::
  193. def get_template(self, step):
  194. return ['myapp/wizard_%s.html' % step, 'myapp/wizard.html']
  195. .. _explained in the template docs: ../templates_python/#the-python-api
  196. ``render_template``
  197. ~~~~~~~~~~~~~~~~~~~
  198. Renders the template for the given step, returning an ``HttpResponse`` object.
  199. Override this method if you want to add a custom context, return a different
  200. MIME type, etc. If you only need to override the template name, use
  201. ``get_template()`` instead.
  202. The template will be rendered with the context documented in the
  203. "Creating templates for the forms" section above.
  204. ``process_step``
  205. ~~~~~~~~~~~~~~~~
  206. Hook for modifying the wizard's internal state, given a fully validated ``Form``
  207. object. The Form is guaranteed to have clean, valid data.
  208. This method should *not* modify any of that data. Rather, it might want to set
  209. ``self.extra_context`` or dynamically alter ``self.form_list``, based on
  210. previously submitted forms.
  211. Note that this method is called every time a page is rendered for *all*
  212. submitted steps.
  213. The function signature::
  214. def process_step(self, request, form, step):
  215. # ...