PageRenderTime 46ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

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