form-wizard.txt 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. ===========
  2. Form wizard
  3. ===========
  4. .. module:: django.contrib.formtools.wizard.views
  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 one of the backends so that the full server-side processing can be
  9. 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: http://en.wikipedia.org/wiki/Wizard_%28software%29
  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 saves the current
  23. state of the wizard in the backend and redirects to the next step.
  24. 3. Step 1 and 2 repeat, for every subsequent form in the wizard.
  25. 4. Once the user has submitted all the forms and all the data has been
  26. validated, the wizard processes the data -- saving it to the database,
  27. sending an email, or whatever the application needs to do.
  28. Usage
  29. =====
  30. This application handles as much machinery for you as possible. Generally,
  31. you just have to do these things:
  32. 1. Define a number of :class:`~django.forms.Form` classes -- one per
  33. wizard page.
  34. 2. Create a :class:`WizardView` subclass that specifies what to do once
  35. all of your forms have been submitted and validated. This also lets
  36. you override some of the wizard's behavior.
  37. 3. Create some templates that render the forms. You can define a single,
  38. generic template to handle every one of the forms, or you can define a
  39. specific template for each form.
  40. 4. Add ``django.contrib.formtools.wizard`` to your
  41. :setting:`INSTALLED_APPS` list in your settings file.
  42. 5. Point your URLconf at your :class:`WizardView` :meth:`~WizardView.as_view` method.
  43. Defining ``Form`` classes
  44. -------------------------
  45. The first step in creating a form wizard is to create the
  46. :class:`~django.forms.Form` classes. These should be standard
  47. :class:`django.forms.Form` classes, covered in the :doc:`forms documentation
  48. </topics/forms/index>`. These classes can live anywhere in your codebase,
  49. but convention is to put them in a file called :file:`forms.py` in your
  50. application.
  51. For example, let's write a "contact form" wizard, where the first page's form
  52. collects the sender's email address and subject, and the second page collects
  53. the message itself. Here's what the :file:`forms.py` might look like::
  54. from django import forms
  55. class ContactForm1(forms.Form):
  56. subject = forms.CharField(max_length=100)
  57. sender = forms.EmailField()
  58. class ContactForm2(forms.Form):
  59. message = forms.CharField(widget=forms.Textarea)
  60. .. note::
  61. In order to use :class:`~django.forms.FileField` in any form, see the
  62. section :ref:`Handling files <wizard-files>` below to learn more about
  63. what to do.
  64. Creating a ``WizardView`` class
  65. -------------------------------
  66. The next step is to create a
  67. :class:`django.contrib.formtools.wizard.view.WizardView` subclass. You can
  68. also use the :class:`SessionWizardView` or :class:`CookieWizardView` class
  69. which preselects the wizard storage backend.
  70. .. note::
  71. To use the :class:`SessionWizardView` follow the instructions
  72. in the :doc:`sessions documentation </topics/http/sessions>` on
  73. how to enable sessions.
  74. We will use the :class:`SessionWizardView` in all examples but is is completely
  75. fine to use the :class:`CookieWizardView` instead. As with your
  76. :class:`~django.forms.Form` classes, this :class:`WizardView` class can live
  77. anywhere in your codebase, but convention is to put it in :file:`views.py`.
  78. The only requirement on this subclass is that it implement a
  79. :meth:`~WizardView.done()` method.
  80. .. method:: WizardView.done(form_list)
  81. This method specifies what should happen when the data for *every* form is
  82. submitted and validated. This method is passed a list of validated
  83. :class:`~django.forms.Form` instances.
  84. In this simplistic example, rather than performing any database operation,
  85. the method simply renders a template of the validated data::
  86. from django.shortcuts import render_to_response
  87. from django.contrib.formtools.wizard.views import SessionWizardView
  88. class ContactWizard(SessionWizardView):
  89. def done(self, form_list, **kwargs):
  90. return render_to_response('done.html', {
  91. 'form_data': [form.cleaned_data for form in form_list],
  92. })
  93. Note that this method will be called via ``POST``, so it really ought to be a
  94. good Web citizen and redirect after processing the data. Here's another
  95. example::
  96. from django.http import HttpResponseRedirect
  97. from django.contrib.formtools.wizard.views import SessionWizardView
  98. class ContactWizard(SessionWizardView):
  99. def done(self, form_list, **kwargs):
  100. do_something_with_the_form_data(form_list)
  101. return HttpResponseRedirect('/page-to-redirect-to-when-done/')
  102. See the section :ref:`Advanced WizardView methods <wizardview-advanced-methods>`
  103. below to learn about more :class:`WizardView` hooks.
  104. Creating templates for the forms
  105. --------------------------------
  106. Next, you'll need to create a template that renders the wizard's forms. By
  107. default, every form uses a template called
  108. :file:`formtools/wizard/wizard_form.html`. You can change this template name
  109. by overriding either the :attr:`~WizardView.template_name` attribute or the
  110. :meth:`~WizardView.get_template_names()` method, which is documented below.
  111. This hook also allows you to use a different template for each form.
  112. This template expects a ``wizard`` object that has various items attached to
  113. it:
  114. * ``form`` -- The :class:`~django.forms.Form` instance for the current
  115. step (either empty or with errors).
  116. * ``steps`` -- A helper object to access the various steps related data:
  117. * ``step0`` -- The current step (zero-based).
  118. * ``step1`` -- The current step (one-based).
  119. * ``count`` -- The total number of steps.
  120. * ``first`` -- The first step.
  121. * ``last`` -- The last step.
  122. * ``current`` -- The current (or first) step.
  123. * ``next`` -- The next step.
  124. * ``prev`` -- The previous step.
  125. * ``index`` -- The index of the current step.
  126. * ``all`` -- A list of all steps of the wizard.
  127. You can supply additional context variables by using the
  128. :meth:`~FormWizard.get_context_data` method of your :class:`FormWizard`
  129. subclass.
  130. Here's a full example template:
  131. .. code-block:: html+django
  132. {% extends "base.html" %}
  133. {% block content %}
  134. <p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p>
  135. <form action="." method="post">{% csrf_token %}
  136. <table>
  137. {{ wizard.management_form }}
  138. {% if wizard.form.forms %}
  139. {{ wizard.form.management_form }}
  140. {% for form in wizard.form.forms %}
  141. {{ form }}
  142. {% endfor %}
  143. {% else %}
  144. {{ wizard.form }}
  145. {% endif %}
  146. {% if wizard.steps.prev %}
  147. <button name="wizard_prev_step" value="{{ wizard.steps.first }}">{% trans "first step" %}</button>
  148. <button name="wizard_prev_step" value="{{ wizard.steps.prev }}">{% trans "prev step" %}</button>
  149. {% endif %}
  150. </table>
  151. <input type="submit">
  152. </form>
  153. {% endblock %}
  154. .. note::
  155. Note that ``{{ wizard.management_form }}`` **must be used** for
  156. the wizard to work properly.
  157. .. _wizard-urlconf:
  158. Hooking the wizard into a URLconf
  159. ---------------------------------
  160. Finally, we need to specify which forms to use in the wizard, and then
  161. deploy the new :class:`WizardView` object a URL in the ``urls.py``. The
  162. wizard's :meth:`as_view` method takes a list of your
  163. :class:`~django.forms.Form` classes as an argument during instantiation::
  164. from django.conf.urls.defaults import patterns
  165. from myapp.forms import ContactForm1, ContactForm2
  166. from myapp.views import ContactWizard
  167. urlpatterns = patterns('',
  168. (r'^contact/$', ContactWizard.as_view([ContactForm1, ContactForm2])),
  169. )
  170. .. _wizardview-advanced-methods:
  171. Advanced ``WizardView`` methods
  172. ===============================
  173. .. class:: WizardView
  174. Aside from the :meth:`~done()` method, :class:`WizardView` offers a few
  175. advanced method hooks that let you customize how your wizard works.
  176. Some of these methods take an argument ``step``, which is a zero-based
  177. counter as string representing the current step of the wizard. (E.g., the
  178. first form is ``'0'`` and the second form is ``'1'``)
  179. .. method:: WizardView.get_form_prefix(step)
  180. Given the step, returns a form prefix to use. By default, this simply uses
  181. the step itself. For more, see the :ref:`form prefix documentation
  182. <form-prefix>`.
  183. .. method:: WizardView.process_step(form)
  184. Hook for modifying the wizard's internal state, given a fully validated
  185. :class:`~django.forms.Form` object. The Form is guaranteed to have clean,
  186. valid data.
  187. Note that this method is called every time a page is rendered for *all*
  188. submitted steps.
  189. The default implementation::
  190. def process_step(self, form):
  191. return self.get_form_step_data(form)
  192. .. method:: WizardView.get_form_initial(step)
  193. Returns a dictionary which will be passed to the form for ``step`` as
  194. ``initial``. If no initial data was provided while initializing the
  195. form wizard, an empty dictionary should be returned.
  196. The default implementation::
  197. def get_form_initial(self, step):
  198. return self.initial_dict.get(step, {})
  199. .. method:: WizardView.get_form_kwargs(step)
  200. Returns a dictionary which will be used as the keyword arguments when
  201. instantiating the form instance on given ``step``.
  202. The default implementation::
  203. def get_form_kwargs(self, step):
  204. return {}
  205. .. method:: WizardView.get_form_instance(step)
  206. Returns an object which will be passed to the form for ``step`` as
  207. ``instance``. If no instance object was provided while initializing
  208. the form wizard, None be returned.
  209. The default implementation::
  210. def get_form_instance(self, step):
  211. return self.instance_dict.get(step, None)
  212. .. method:: WizardView.get_context_data(form, **kwargs)
  213. Returns the template context for a step. You can overwrite this method
  214. to add more data for all or some steps. This method returns a dictionary
  215. containing the rendered form step.
  216. The default template context variables are:
  217. * Any extra data the storage backend has stored
  218. * ``form`` -- form instance of the current step
  219. * ``wizard`` -- the wizard instance itself
  220. Example to add extra variables for a specific step::
  221. def get_context_data(self, form, **kwargs):
  222. context = super(MyWizard, self).get_context_data(form, **kwargs)
  223. if self.steps.current == 'my_step_name':
  224. context.update({'another_var': True})
  225. return context
  226. .. method:: WizardView.get_wizard_name()
  227. This method can be used to change the wizard's internal name.
  228. Default implementation::
  229. def get_wizard_name(self):
  230. return normalize_name(self.__class__.__name__)
  231. .. method:: WizardView.get_prefix()
  232. This method returns a prefix for the storage backends. These backends use
  233. the prefix to fetch the correct data for the wizard. (Multiple wizards
  234. could save their data in one session)
  235. You can change this method to make the wizard data prefix more unique to,
  236. e.g. have multiple instances of one wizard in one session.
  237. Default implementation::
  238. def get_prefix(self):
  239. return self.wizard_name
  240. .. method:: WizardView.get_form(step=None, data=None, files=None)
  241. This method constructs the form for a given ``step``. If no ``step`` is
  242. defined, the current step will be determined automatically.
  243. The method gets three arguments:
  244. * ``step`` -- The step for which the form instance should be generated.
  245. * ``data`` -- Gets passed to the form's data argument
  246. * ``files`` -- Gets passed to the form's files argument
  247. You can override this method to add extra arguments to the form instance.
  248. Example code to add a user attribute to the form on step 2::
  249. def get_form(self, step=None, data=None, files=None):
  250. form = super(MyWizard, self).get_form(step, data, files)
  251. if step == '1':
  252. form.user = self.request.user
  253. return form
  254. .. method:: WizardView.process_step(form)
  255. This method gives you a way to post-process the form data before the data
  256. gets stored within the storage backend. By default it just passed the
  257. form.data dictionary. You should not manipulate the data here but you can
  258. use the data to do some extra work if needed (e.g. set storage extra data).
  259. Default implementation::
  260. def process_step(self, form):
  261. return self.get_form_step_data(form)
  262. .. method:: WizardView.process_step_files(form)
  263. This method gives you a way to post-process the form files before the
  264. files gets stored within the storage backend. By default it just passed
  265. the ``form.files`` dictionary. You should not manipulate the data here
  266. but you can use the data to do some extra work if needed (e.g. set storage
  267. extra data).
  268. Default implementation::
  269. def process_step_files(self, form):
  270. return self.get_form_step_files(form)
  271. .. method:: WizardView.render_revalidation_failure(step, form, **kwargs)
  272. When the wizard thinks, all steps passed it revalidates all forms with the
  273. data from the backend storage.
  274. If any of the forms don't validate correctly, this method gets called.
  275. This method expects two arguments, ``step`` and ``form``.
  276. The default implementation resets the current step to the first failing
  277. form and redirects the user to the invalid form.
  278. Default implementation::
  279. def render_revalidation_failure(self, step, form, **kwargs):
  280. self.storage.current_step = step
  281. return self.render(form, **kwargs)
  282. .. method:: WizardView.get_form_step_data(form)
  283. This method fetches the form data from and returns the dictionary. You
  284. can use this method to manipulate the values before the data gets stored
  285. in the storage backend.
  286. Default implementation::
  287. def get_form_step_data(self, form):
  288. return form.data
  289. .. method:: WizardView.get_form_step_files(form)
  290. This method returns the form files. You can use this method to manipulate
  291. the files before the data gets stored in the storage backend.
  292. Default implementation::
  293. def get_form_step_files(self, form):
  294. return form.files
  295. .. method:: WizardView.render(form, **kwargs)
  296. This method gets called after the get or post request was handled. You can
  297. hook in this method to, e.g. change the type of http response.
  298. Default implementation::
  299. def render(self, form=None, **kwargs):
  300. form = form or self.get_form()
  301. context = self.get_context_data(form, **kwargs)
  302. return self.render_to_response(context)
  303. Providing initial data for the forms
  304. ====================================
  305. .. attribute:: WizardView.initial_dict
  306. Initial data for a wizard's :class:`~django.forms.Form` objects can be
  307. provided using the optional :attr:`~Wizard.initial_dict` keyword argument.
  308. This argument should be a dictionary mapping the steps to dictionaries
  309. containing the initial data for each step. The dictionary of initial data
  310. will be passed along to the constructor of the step's
  311. :class:`~django.forms.Form`::
  312. >>> from myapp.forms import ContactForm1, ContactForm2
  313. >>> from myapp.views import ContactWizard
  314. >>> initial = {
  315. ... '0': {'subject': 'Hello', 'sender': 'user@example.com'},
  316. ... '1': {'message': 'Hi there!'}
  317. ... }
  318. >>> wiz = ContactWizard.as_view([ContactForm1, ContactForm2], initial_dict=initial)
  319. >>> form1 = wiz.get_form('0')
  320. >>> form2 = wiz.get_form('1')
  321. >>> form1.initial
  322. {'sender': 'user@example.com', 'subject': 'Hello'}
  323. >>> form2.initial
  324. {'message': 'Hi there!'}
  325. The ``initial_dict`` can also take a list of dictionaries for a specific
  326. step if the step is a ``FormSet``.
  327. .. _wizard-files:
  328. Handling files
  329. ==============
  330. To handle :class:`~django.forms.FileField` within any step form of the wizard,
  331. you have to add a :attr:`file_storage` to your :class:`WizardView` subclass.
  332. This storage will temporarilyy store the uploaded files for the wizard. The
  333. :attr:`file_storage` attribute should be a
  334. :class:`~django.core.files.storage.Storage` subclass.
  335. .. warning::
  336. Please remember to take care of removing old files as the
  337. :class:`WizardView` won't remove any files, whether the wizard gets
  338. finished correctly or not.
  339. Conditionally view/skip specific steps
  340. ======================================
  341. .. attribute:: WizardView.condition_dict
  342. The :meth:`~WizardView.as_view` accepts a ``condition_dict`` argument. You can pass a
  343. dictionary of boolean values or callables. The key should match the steps
  344. name (e.g. '0', '1').
  345. If the value of a specific step is callable it will be called with the
  346. :class:`WizardView` instance as the only argument. If the return value is true,
  347. the step's form will be used.
  348. This example provides a contact form including a condition. The condition is
  349. used to show a message form only if a checkbox in the first step was checked.
  350. The steps are defined in a ``forms.py``::
  351. from django import forms
  352. class ContactForm1(forms.Form):
  353. subject = forms.CharField(max_length=100)
  354. sender = forms.EmailField()
  355. leave_message = forms.BooleanField(required=False)
  356. class ContactForm2(forms.Form):
  357. message = forms.CharField(widget=forms.Textarea)
  358. We define our wizard in a ``views.py``::
  359. from django.shortcuts import render_to_response
  360. from django.contrib.formtools.wizard.views import SessionWizardView
  361. def show_message_form_condition(wizard):
  362. # try to get the cleaned data of step 1
  363. cleaned_data = wizard.get_cleaned_data_for_step('0') or {}
  364. # check if the field ``leave_message`` was checked.
  365. return cleaned_data.get('leave_message', True)
  366. class ContactWizard(SessionWizardView):
  367. def done(self, form_list, **kwargs):
  368. return render_to_response('done.html', {
  369. 'form_data': [form.cleaned_data for form in form_list],
  370. })
  371. We need to add the ``ContactWizard`` to our ``urls.py`` file::
  372. from django.conf.urls.defaults import pattern
  373. from myapp.forms import ContactForm1, ContactForm2
  374. from myapp.views import ContactWizard, show_message_form_condition
  375. contact_forms = [ContactForm1, ContactForm2]
  376. urlpatterns = patterns('',
  377. (r'^contact/$', ContactWizard.as_view(contact_forms,
  378. condition_dict={'1': show_message_form_condition}
  379. )),
  380. )
  381. As you can see, we defined a ``show_message_form_condition`` next to our
  382. :class:`WizardView` subclass and added a ``condition_dict`` argument to the
  383. :meth:`~WizardView.as_view` method. The key refers to the second wizard step
  384. (because of the zero based step index).
  385. How to work with ModelForm and ModelFormSet
  386. ===========================================
  387. The WizardView supports :class:`~django.forms.ModelForm` and
  388. :class:`~django.forms.ModelFormSet`. Additionally to the ``initial_dict``,
  389. the :meth:`~WizardView.as_view` method takes a ``instance_dict`` argument
  390. with a list of instances for the ``ModelForm`` and ``ModelFormSet``.
  391. Usage of NamedUrlWizardView
  392. ===========================
  393. .. class:: NamedUrlWizardView
  394. There is a :class:`WizardView` subclass which adds named-urls support to the wizard.
  395. By doing this, you can have single urls for every step.
  396. To use the named urls, you have to change the ``urls.py``.
  397. Below you will see an example of a contact wizard with two steps, step 1 with
  398. "contactdata" as its name and step 2 with "leavemessage" as its name.
  399. Additionally you have to pass two more arguments to the
  400. :meth:`~WizardView.as_view` method:
  401. * ``url_name`` -- the name of the url (as provided in the urls.py)
  402. * ``done_step_name`` -- the name in the url for the done step
  403. Example code for the changed ``urls.py`` file::
  404. from django.conf.urls.defaults import url, patterns
  405. from myapp.forms import ContactForm1, ContactForm2
  406. from myapp.views import ContactWizard
  407. named_contact_forms = (
  408. ('contactdata', ContactForm1),
  409. ('leavemessage', ContactForm2),
  410. )
  411. contact_wizard = ContactWizard.as_view(named_contact_forms,
  412. url_name='contact_step', done_step_name='finished')
  413. urlpatterns = patterns('',
  414. url(r'^contact/(?P<step>.+)/$', contact_wizard, name='contact_step'),
  415. url(r'^contact/$', contact_wizard, name='contact'),
  416. )