form-wizard.txt 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  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`` to your
  41. :setting:`INSTALLED_APPS` list in your settings file.
  42. 5. Point your URLconf at your :class:`WizardView` :meth:`~WizardView.as_view`
  43. method.
  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,
  50. but convention is to put them in a file called :file:`forms.py` 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 email address and subject, and the second page collects
  54. the message itself. Here's what the :file:`forms.py` 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. .. note::
  62. In order to use :class:`~django.forms.FileField` in any form, see the
  63. section :ref:`Handling files <wizard-files>` below to learn more about
  64. what to do.
  65. Creating a ``WizardView`` subclass
  66. ----------------------------------
  67. .. class:: SessionWizardView
  68. .. class:: CookieWizardView
  69. The next step is to create a
  70. :class:`django.contrib.formtools.wizard.views.WizardView` subclass. You can
  71. also use the :class:`SessionWizardView` or :class:`CookieWizardView` classes
  72. which preselect the backend used for storing information during execution of the
  73. wizard (as their names indicate, server-side sessions and browser cookies
  74. respectively).
  75. .. note::
  76. To use the :class:`SessionWizardView` follow the instructions
  77. in the :doc:`sessions documentation </topics/http/sessions>` on
  78. how to enable sessions.
  79. We will use the :class:`SessionWizardView` in all examples but is is completely
  80. fine to use the :class:`CookieWizardView` instead. As with your
  81. :class:`~django.forms.Form` classes, this :class:`WizardView` class can live
  82. anywhere in your codebase, but convention is to put it in :file:`views.py`.
  83. The only requirement on this subclass is that it implement a
  84. :meth:`~WizardView.done()` method.
  85. .. method:: WizardView.done(form_list, form_dict, **kwargs)
  86. This method specifies what should happen when the data for *every* form is
  87. submitted and validated. This method is passed a list and dictionary of
  88. validated :class:`~django.forms.Form` instances.
  89. In this simplistic example, rather than performing any database operation,
  90. the method simply renders a template of the validated data::
  91. from django.shortcuts import render_to_response
  92. from django.contrib.formtools.wizard.views import SessionWizardView
  93. class ContactWizard(SessionWizardView):
  94. def done(self, form_list, **kwargs):
  95. return render_to_response('done.html', {
  96. 'form_data': [form.cleaned_data for form in form_list],
  97. })
  98. Note that this method will be called via ``POST``, so it really ought to be a
  99. good Web citizen and redirect after processing the data. Here's another
  100. example::
  101. from django.http import HttpResponseRedirect
  102. from django.contrib.formtools.wizard.views import SessionWizardView
  103. class ContactWizard(SessionWizardView):
  104. def done(self, form_list, **kwargs):
  105. do_something_with_the_form_data(form_list)
  106. return HttpResponseRedirect('/page-to-redirect-to-when-done/')
  107. In addition to ``form_list``, the :meth:`~WizardView.done` method
  108. is passed a ``form_dict``, which allows you to access the wizard's
  109. forms based on their step names. This is especially useful when using
  110. :class:`NamedUrlWizardView`, for example::
  111. def done(self, form_list, form_dict, **kwargs):
  112. user = form_dict['user'].save()
  113. credit_card = form_dict['credit_card'].save()
  114. # ...
  115. .. versionchanged:: 1.7
  116. Previously, the ``form_dict`` argument wasn't passed to the
  117. ``done`` method.
  118. See the section :ref:`Advanced WizardView methods <wizardview-advanced-methods>`
  119. below to learn about more :class:`WizardView` hooks.
  120. Creating templates for the forms
  121. --------------------------------
  122. Next, you'll need to create a template that renders the wizard's forms. By
  123. default, every form uses a template called
  124. :file:`formtools/wizard/wizard_form.html`. You can change this template name
  125. by overriding either the
  126. :attr:`~django.views.generic.base.TemplateResponseMixin.template_name` attribute
  127. or the
  128. :meth:`~django.views.generic.base.TemplateResponseMixin.get_template_names()`
  129. method, which are documented in the
  130. :class:`~django.views.generic.base.TemplateResponseMixin` documentation. The
  131. latter one allows you to use a different template for each form (:ref:`see the
  132. example below <wizard-template-for-each-form>`).
  133. This template expects a ``wizard`` object that has various items attached to
  134. it:
  135. * ``form`` -- The :class:`~django.forms.Form` or
  136. :class:`~django.forms.formsets.BaseFormSet` instance for the current step
  137. (either empty or with errors).
  138. * ``steps`` -- A helper object to access the various steps related data:
  139. * ``step0`` -- The current step (zero-based).
  140. * ``step1`` -- The current step (one-based).
  141. * ``count`` -- The total number of steps.
  142. * ``first`` -- The first step.
  143. * ``last`` -- The last step.
  144. * ``current`` -- The current (or first) step.
  145. * ``next`` -- The next step.
  146. * ``prev`` -- The previous step.
  147. * ``index`` -- The index of the current step.
  148. * ``all`` -- A list of all steps of the wizard.
  149. You can supply additional context variables by using the
  150. :meth:`~WizardView.get_context_data` method of your :class:`WizardView`
  151. subclass.
  152. Here's a full example template:
  153. .. code-block:: html+django
  154. {% extends "base.html" %}
  155. {% load i18n %}
  156. {% block head %}
  157. {{ wizard.form.media }}
  158. {% endblock %}
  159. {% block content %}
  160. <p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p>
  161. <form action="" method="post">{% csrf_token %}
  162. <table>
  163. {{ wizard.management_form }}
  164. {% if wizard.form.forms %}
  165. {{ wizard.form.management_form }}
  166. {% for form in wizard.form.forms %}
  167. {{ form }}
  168. {% endfor %}
  169. {% else %}
  170. {{ wizard.form }}
  171. {% endif %}
  172. </table>
  173. {% if wizard.steps.prev %}
  174. <button name="wizard_goto_step" type="submit" value="{{ wizard.steps.first }}">{% trans "first step" %}</button>
  175. <button name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">{% trans "prev step" %}</button>
  176. {% endif %}
  177. <input type="submit" value="{% trans "submit" %}"/>
  178. </form>
  179. {% endblock %}
  180. .. note::
  181. Note that ``{{ wizard.management_form }}`` **must be used** for
  182. the wizard to work properly.
  183. .. _wizard-urlconf:
  184. Hooking the wizard into a URLconf
  185. ---------------------------------
  186. .. method:: WizardView.as_view()
  187. Finally, we need to specify which forms to use in the wizard, and then
  188. deploy the new :class:`WizardView` object at a URL in the ``urls.py``. The
  189. wizard's ``as_view()`` method takes a list of your
  190. :class:`~django.forms.Form` classes as an argument during instantiation::
  191. from django.conf.urls import patterns
  192. from myapp.forms import ContactForm1, ContactForm2
  193. from myapp.views import ContactWizard
  194. urlpatterns = patterns('',
  195. (r'^contact/$', ContactWizard.as_view([ContactForm1, ContactForm2])),
  196. )
  197. .. versionchanged:: 1.6
  198. You can also pass the form list as a class attribute named ``form_list``::
  199. class ContactWizard(WizardView):
  200. form_list = [ContactForm1, ContactForm2]
  201. .. _wizard-template-for-each-form:
  202. Using a different template for each form
  203. ----------------------------------------
  204. As mentioned above, you may specify a different template for each form.
  205. Consider an example using a form wizard to implement a multi-step checkout
  206. process for an online store. In the first step, the user specifies a billing
  207. and shipping address. In the second step, the user chooses payment type. If
  208. they chose to pay by credit card, they will enter credit card information in
  209. the next step. In the final step, they will confirm the purchase.
  210. Here's what the view code might look like::
  211. from django.http import HttpResponseRedirect
  212. from django.contrib.formtools.wizard.views import SessionWizardView
  213. FORMS = [("address", myapp.forms.AddressForm),
  214. ("paytype", myapp.forms.PaymentChoiceForm),
  215. ("cc", myapp.forms.CreditCardForm),
  216. ("confirmation", myapp.forms.OrderForm)]
  217. TEMPLATES = {"address": "checkout/billingaddress.html",
  218. "paytype": "checkout/paymentmethod.html",
  219. "cc": "checkout/creditcard.html",
  220. "confirmation": "checkout/confirmation.html"}
  221. def pay_by_credit_card(wizard):
  222. """Return true if user opts to pay by credit card"""
  223. # Get cleaned data from payment step
  224. cleaned_data = wizard.get_cleaned_data_for_step('paytype') or {'method': 'none'}
  225. # Return true if the user selected credit card
  226. return cleaned_data['method'] == 'cc'
  227. class OrderWizard(SessionWizardView):
  228. def get_template_names(self):
  229. return [TEMPLATES[self.steps.current]]
  230. def done(self, form_list, **kwargs):
  231. do_something_with_the_form_data(form_list)
  232. return HttpResponseRedirect('/page-to-redirect-to-when-done/')
  233. ...
  234. The ``urls.py`` file would contain something like::
  235. urlpatterns = patterns('',
  236. (r'^checkout/$', OrderWizard.as_view(FORMS, condition_dict={'cc': pay_by_credit_card})),
  237. )
  238. .. versionchanged:: 1.6
  239. The ``condiction_dict`` can be passed as attribute for the ``as_view()`
  240. method or as a class attribute named ``condition_dict``::
  241. class OrderWizard(WizardView):
  242. condition_dict = {'cc': pay_by_credit_card}
  243. Note that the ``OrderWizard`` object is initialized with a list of pairs.
  244. The first element in the pair is a string that corresponds to the name of the
  245. step and the second is the form class.
  246. In this example, the
  247. :meth:`~django.views.generic.base.TemplateResponseMixin.get_template_names()`
  248. method returns a list containing a single template, which is selected based on
  249. the name of the current step.
  250. .. _wizardview-advanced-methods:
  251. Advanced ``WizardView`` methods
  252. ===============================
  253. .. class:: WizardView
  254. Aside from the :meth:`~done()` method, :class:`WizardView` offers a few
  255. advanced method hooks that let you customize how your wizard works.
  256. Some of these methods take an argument ``step``, which is a zero-based
  257. counter as string representing the current step of the wizard. (E.g., the
  258. first form is ``'0'`` and the second form is ``'1'``)
  259. .. method:: WizardView.get_form_prefix(step=None, form=None)
  260. Returns the prefix which will be used when calling the form for the given
  261. step. ``step`` contains the step name, ``form`` the form class which will
  262. be called with the returned prefix.
  263. If no ``step`` is given, it will be determined automatically. By default,
  264. this simply uses the step itself and the ``form`` parameter is not used.
  265. For more, see the :ref:`form prefix documentation <form-prefix>`.
  266. .. method:: WizardView.get_form_initial(step)
  267. Returns a dictionary which will be passed as the
  268. :attr:`~django.forms.Form.initial` argument when instantiating the Form
  269. instance for step ``step``. If no initial data was provided while
  270. initializing the form wizard, an empty dictionary should be returned.
  271. The default implementation::
  272. def get_form_initial(self, step):
  273. return self.initial_dict.get(step, {})
  274. .. method:: WizardView.get_form_kwargs(step)
  275. Returns a dictionary which will be used as the keyword arguments when
  276. instantiating the form instance on given ``step``.
  277. The default implementation::
  278. def get_form_kwargs(self, step):
  279. return {}
  280. .. method:: WizardView.get_form_instance(step)
  281. This method will be called only if a :class:`~django.forms.ModelForm` is
  282. used as the form for step ``step``.
  283. Returns an :class:`~django.db.models.Model` object which will be passed as
  284. the ``instance`` argument when instantiating the ``ModelForm`` for step
  285. ``step``. If no instance object was provided while initializing the form
  286. wizard, ``None`` will be returned.
  287. The default implementation::
  288. def get_form_instance(self, step):
  289. return self.instance_dict.get(step, None)
  290. .. method:: WizardView.get_context_data(form, **kwargs)
  291. Returns the template context for a step. You can overwrite this method
  292. to add more data for all or some steps. This method returns a dictionary
  293. containing the rendered form step.
  294. The default template context variables are:
  295. * Any extra data the storage backend has stored
  296. * ``form`` -- form instance of the current step
  297. * ``wizard`` -- the wizard instance itself
  298. Example to add extra variables for a specific step::
  299. def get_context_data(self, form, **kwargs):
  300. context = super(MyWizard, self).get_context_data(form=form, **kwargs)
  301. if self.steps.current == 'my_step_name':
  302. context.update({'another_var': True})
  303. return context
  304. .. method:: WizardView.get_prefix(*args, **kwargs)
  305. This method returns a prefix for use by the storage backends. Backends use
  306. the prefix as a mechanism to allow data to be stored separately for each
  307. wizard. This allows wizards to store their data in a single backend
  308. without overwriting each other.
  309. You can change this method to make the wizard data prefix more unique to,
  310. e.g. have multiple instances of one wizard in one session.
  311. Default implementation::
  312. def get_prefix(self, *args, **kwargs):
  313. # use the lowercase underscore version of the class name
  314. return normalize_name(self.__class__.__name__)
  315. .. method:: WizardView.get_form(step=None, data=None, files=None)
  316. This method constructs the form for a given ``step``. If no ``step`` is
  317. defined, the current step will be determined automatically. If you override
  318. ``get_form``, however, you will need to set ``step`` yourself using
  319. ``self.steps.current`` as in the example below. The method gets three
  320. arguments:
  321. * ``step`` -- The step for which the form instance should be generated.
  322. * ``data`` -- Gets passed to the form's data argument
  323. * ``files`` -- Gets passed to the form's files argument
  324. You can override this method to add extra arguments to the form instance.
  325. Example code to add a user attribute to the form on step 2::
  326. def get_form(self, step=None, data=None, files=None):
  327. form = super(MyWizard, self).get_form(step, data, files)
  328. # determine the step if not given
  329. if step is None:
  330. step = self.steps.current
  331. if step == '1':
  332. form.user = self.request.user
  333. return form
  334. .. method:: WizardView.process_step(form)
  335. Hook for modifying the wizard's internal state, given a fully validated
  336. :class:`~django.forms.Form` object. The Form is guaranteed to have clean,
  337. valid data.
  338. This method gives you a way to post-process the form data before the data
  339. gets stored within the storage backend. By default it just returns the
  340. ``form.data`` dictionary. You should not manipulate the data here but you
  341. can use it to do some extra work if needed (e.g. set storage extra data).
  342. Note that this method is called every time a page is rendered for *all*
  343. submitted steps.
  344. The default implementation::
  345. def process_step(self, form):
  346. return self.get_form_step_data(form)
  347. .. method:: WizardView.process_step_files(form)
  348. This method gives you a way to post-process the form files before the
  349. files gets stored within the storage backend. By default it just returns
  350. the ``form.files`` dictionary. You should not manipulate the data here
  351. but you can use it to do some extra work if needed (e.g. set storage
  352. extra data).
  353. Default implementation::
  354. def process_step_files(self, form):
  355. return self.get_form_step_files(form)
  356. .. method:: WizardView.render_goto_step(step, goto_step, **kwargs)
  357. .. versionadded:: 1.6
  358. This method is called when the step should be changed to something else
  359. than the next step. By default, this method just stores the requested
  360. step ``goto_step`` in the storage and then renders the new step.
  361. If you want to store the entered data of the current step before rendering
  362. the next step, you can overwrite this method.
  363. .. method:: WizardView.render_revalidation_failure(step, form, **kwargs)
  364. When the wizard thinks all steps have passed it revalidates all forms with
  365. the data from the backend storage.
  366. If any of the forms don't validate correctly, this method gets called.
  367. This method expects two arguments, ``step`` and ``form``.
  368. The default implementation resets the current step to the first failing
  369. form and redirects the user to the invalid form.
  370. Default implementation::
  371. def render_revalidation_failure(self, step, form, **kwargs):
  372. self.storage.current_step = step
  373. return self.render(form, **kwargs)
  374. .. method:: WizardView.get_form_step_data(form)
  375. This method fetches the data from the ``form`` Form instance and returns the
  376. dictionary. You can use this method to manipulate the values before the data
  377. gets stored in the storage backend.
  378. Default implementation::
  379. def get_form_step_data(self, form):
  380. return form.data
  381. .. method:: WizardView.get_form_step_files(form)
  382. This method returns the form files. You can use this method to manipulate
  383. the files before the data gets stored in the storage backend.
  384. Default implementation::
  385. def get_form_step_files(self, form):
  386. return form.files
  387. .. method:: WizardView.render(form, **kwargs)
  388. This method gets called after the GET or POST request has been handled. You
  389. can hook in this method to, e.g. change the type of HTTP response.
  390. Default implementation::
  391. def render(self, form=None, **kwargs):
  392. form = form or self.get_form()
  393. context = self.get_context_data(form=form, **kwargs)
  394. return self.render_to_response(context)
  395. .. method:: WizardView.get_cleaned_data_for_step(step)
  396. This method returns the cleaned data for a given ``step``. Before returning
  397. the cleaned data, the stored values are revalidated through the form. If
  398. the data doesn't validate, ``None`` will be returned.
  399. .. method:: WizardView.get_all_cleaned_data()
  400. This method returns a merged dictionary of all form steps' ``cleaned_data``
  401. dictionaries. If a step contains a ``FormSet``, the key will be prefixed
  402. with ``formset-`` and contain a list of the formset's ``cleaned_data``
  403. dictionaries. Note that if two or more steps have a field with the same
  404. name, the value for that field from the latest step will overwrite the
  405. value from any earlier steps.
  406. Providing initial data for the forms
  407. ====================================
  408. .. attribute:: WizardView.initial_dict
  409. Initial data for a wizard's :class:`~django.forms.Form` objects can be
  410. provided using the optional :attr:`~WizardView.initial_dict` keyword
  411. argument. This argument should be a dictionary mapping the steps to
  412. dictionaries containing the initial data for each step. The dictionary of
  413. initial data will be passed along to the constructor of the step's
  414. :class:`~django.forms.Form`::
  415. >>> from myapp.forms import ContactForm1, ContactForm2
  416. >>> from myapp.views import ContactWizard
  417. >>> initial = {
  418. ... '0': {'subject': 'Hello', 'sender': 'user@example.com'},
  419. ... '1': {'message': 'Hi there!'}
  420. ... }
  421. >>> # This example is illustrative only and isn't meant to be run in
  422. >>> # the shell since it requires an HttpRequest to pass to the view.
  423. >>> wiz = ContactWizard.as_view([ContactForm1, ContactForm2], initial_dict=initial)(request)
  424. >>> form1 = wiz.get_form('0')
  425. >>> form2 = wiz.get_form('1')
  426. >>> form1.initial
  427. {'sender': 'user@example.com', 'subject': 'Hello'}
  428. >>> form2.initial
  429. {'message': 'Hi there!'}
  430. The ``initial_dict`` can also take a list of dictionaries for a specific
  431. step if the step is a ``FormSet``.
  432. .. versionchanged:: 1.6
  433. The ``initial_dict`` can also be added as a class attribute named
  434. ``initial_dict`` to avoid having the initial data in the ``urls.py``.
  435. .. _wizard-files:
  436. Handling files
  437. ==============
  438. .. attribute:: WizardView.file_storage
  439. To handle :class:`~django.forms.FileField` within any step form of the wizard,
  440. you have to add a ``file_storage`` to your :class:`WizardView` subclass.
  441. This storage will temporarily store the uploaded files for the wizard. The
  442. ``file_storage`` attribute should be a
  443. :class:`~django.core.files.storage.Storage` subclass.
  444. Django provides a built-in storage class (see :ref:`the built-in filesystem
  445. storage class <builtin-fs-storage>`)::
  446. from django.conf import settings
  447. from django.core.files.storage import FileSystemStorage
  448. class CustomWizardView(WizardView):
  449. ...
  450. file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'photos'))
  451. .. warning::
  452. Please remember to take care of removing old files as the
  453. :class:`WizardView` won't remove any files, whether the wizard gets
  454. finished correctly or not.
  455. Conditionally view/skip specific steps
  456. ======================================
  457. .. attribute:: WizardView.condition_dict
  458. The :meth:`~WizardView.as_view` method accepts a ``condition_dict`` argument.
  459. You can pass a dictionary of boolean values or callables. The key should match
  460. the steps names (e.g. '0', '1').
  461. If the value of a specific step is callable it will be called with the
  462. :class:`WizardView` instance as the only argument. If the return value is true,
  463. the step's form will be used.
  464. This example provides a contact form including a condition. The condition is
  465. used to show a message form only if a checkbox in the first step was checked.
  466. The steps are defined in a ``forms.py`` file::
  467. from django import forms
  468. class ContactForm1(forms.Form):
  469. subject = forms.CharField(max_length=100)
  470. sender = forms.EmailField()
  471. leave_message = forms.BooleanField(required=False)
  472. class ContactForm2(forms.Form):
  473. message = forms.CharField(widget=forms.Textarea)
  474. We define our wizard in a ``views.py``::
  475. from django.shortcuts import render_to_response
  476. from django.contrib.formtools.wizard.views import SessionWizardView
  477. def show_message_form_condition(wizard):
  478. # try to get the cleaned data of step 1
  479. cleaned_data = wizard.get_cleaned_data_for_step('0') or {}
  480. # check if the field ``leave_message`` was checked.
  481. return cleaned_data.get('leave_message', True)
  482. class ContactWizard(SessionWizardView):
  483. def done(self, form_list, **kwargs):
  484. return render_to_response('done.html', {
  485. 'form_data': [form.cleaned_data for form in form_list],
  486. })
  487. We need to add the ``ContactWizard`` to our ``urls.py`` file::
  488. from django.conf.urls import patterns
  489. from myapp.forms import ContactForm1, ContactForm2
  490. from myapp.views import ContactWizard, show_message_form_condition
  491. contact_forms = [ContactForm1, ContactForm2]
  492. urlpatterns = patterns('',
  493. (r'^contact/$', ContactWizard.as_view(contact_forms,
  494. condition_dict={'1': show_message_form_condition}
  495. )),
  496. )
  497. As you can see, we defined a ``show_message_form_condition`` next to our
  498. :class:`WizardView` subclass and added a ``condition_dict`` argument to the
  499. :meth:`~WizardView.as_view` method. The key refers to the second wizard step
  500. (because of the zero based step index).
  501. How to work with ModelForm and ModelFormSet
  502. ===========================================
  503. .. attribute:: WizardView.instance_dict
  504. WizardView supports :doc:`ModelForms </topics/forms/modelforms>` and
  505. :ref:`ModelFormSets <model-formsets>`. Additionally to
  506. :attr:`~WizardView.initial_dict`, the :meth:`~WizardView.as_view` method takes
  507. an ``instance_dict`` argument that should contain model instances for steps
  508. based on ``ModelForm`` and querysets for steps based on ``ModelFormSet``.
  509. Usage of ``NamedUrlWizardView``
  510. ===============================
  511. .. class:: NamedUrlWizardView
  512. .. class:: NamedUrlSessionWizardView
  513. .. class:: NamedUrlCookieWizardView
  514. There is a :class:`WizardView` subclass which adds named-urls support to the
  515. wizard. By doing this, you can have single urls for every step. You can also
  516. use the :class:`NamedUrlSessionWizardView` or :class:`NamedUrlCookieWizardView`
  517. classes which preselect the backend used for storing information (server-side
  518. sessions and browser cookies respectively).
  519. To use the named urls, you have to change the ``urls.py``.
  520. Below you will see an example of a contact wizard with two steps, step 1 with
  521. ``"contactdata"`` as its name and step 2 with ``"leavemessage"`` as its name.
  522. Additionally you have to pass two more arguments to the
  523. :meth:`~WizardView.as_view` method:
  524. * ``url_name`` -- the name of the url (as provided in the urls.py)
  525. * ``done_step_name`` -- the name in the url for the done step
  526. Example code for the changed ``urls.py`` file::
  527. from django.conf.urls import url, patterns
  528. from myapp.forms import ContactForm1, ContactForm2
  529. from myapp.views import ContactWizard
  530. named_contact_forms = (
  531. ('contactdata', ContactForm1),
  532. ('leavemessage', ContactForm2),
  533. )
  534. contact_wizard = ContactWizard.as_view(named_contact_forms,
  535. url_name='contact_step', done_step_name='finished')
  536. urlpatterns = patterns('',
  537. url(r'^contact/(?P<step>.+)/$', contact_wizard, name='contact_step'),
  538. url(r'^contact/$', contact_wizard, name='contact'),
  539. )
  540. Advanced ``NamedUrlWizardView`` methods
  541. =======================================
  542. .. method:: NamedUrlWizardView.get_step_url(step)
  543. This method returns the URL for a specific step.
  544. Default implementation::
  545. def get_step_url(self, step):
  546. return reverse(self.url_name, kwargs={'step': step})