form-wizard.txt 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759
  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 url
  192. from myapp.forms import ContactForm1, ContactForm2
  193. from myapp.views import ContactWizard
  194. urlpatterns = [
  195. url(r'^contact/$', ContactWizard.as_view([ContactForm1, ContactForm2])),
  196. ]
  197. You can also pass the form list as a class attribute named ``form_list``::
  198. class ContactWizard(WizardView):
  199. form_list = [ContactForm1, ContactForm2]
  200. .. _wizard-template-for-each-form:
  201. Using a different template for each form
  202. ----------------------------------------
  203. As mentioned above, you may specify a different template for each form.
  204. Consider an example using a form wizard to implement a multi-step checkout
  205. process for an online store. In the first step, the user specifies a billing
  206. and shipping address. In the second step, the user chooses payment type. If
  207. they chose to pay by credit card, they will enter credit card information in
  208. the next step. In the final step, they will confirm the purchase.
  209. Here's what the view code might look like::
  210. from django.http import HttpResponseRedirect
  211. from django.contrib.formtools.wizard.views import SessionWizardView
  212. FORMS = [("address", myapp.forms.AddressForm),
  213. ("paytype", myapp.forms.PaymentChoiceForm),
  214. ("cc", myapp.forms.CreditCardForm),
  215. ("confirmation", myapp.forms.OrderForm)]
  216. TEMPLATES = {"address": "checkout/billingaddress.html",
  217. "paytype": "checkout/paymentmethod.html",
  218. "cc": "checkout/creditcard.html",
  219. "confirmation": "checkout/confirmation.html"}
  220. def pay_by_credit_card(wizard):
  221. """Return true if user opts to pay by credit card"""
  222. # Get cleaned data from payment step
  223. cleaned_data = wizard.get_cleaned_data_for_step('paytype') or {'method': 'none'}
  224. # Return true if the user selected credit card
  225. return cleaned_data['method'] == 'cc'
  226. class OrderWizard(SessionWizardView):
  227. def get_template_names(self):
  228. return [TEMPLATES[self.steps.current]]
  229. def done(self, form_list, **kwargs):
  230. do_something_with_the_form_data(form_list)
  231. return HttpResponseRedirect('/page-to-redirect-to-when-done/')
  232. ...
  233. The ``urls.py`` file would contain something like::
  234. urlpatterns = [
  235. url(r'^checkout/$', OrderWizard.as_view(FORMS, condition_dict={'cc': pay_by_credit_card})),
  236. ]
  237. The ``condition_dict`` can be passed as attribute for the ``as_view()`
  238. method or as a class attribute named ``condition_dict``::
  239. class OrderWizard(WizardView):
  240. condition_dict = {'cc': pay_by_credit_card}
  241. Note that the ``OrderWizard`` object is initialized with a list of pairs.
  242. The first element in the pair is a string that corresponds to the name of the
  243. step and the second is the form class.
  244. In this example, the
  245. :meth:`~django.views.generic.base.TemplateResponseMixin.get_template_names()`
  246. method returns a list containing a single template, which is selected based on
  247. the name of the current step.
  248. .. _wizardview-advanced-methods:
  249. Advanced ``WizardView`` methods
  250. ===============================
  251. .. class:: WizardView
  252. Aside from the :meth:`~done()` method, :class:`WizardView` offers a few
  253. advanced method hooks that let you customize how your wizard works.
  254. Some of these methods take an argument ``step``, which is a zero-based
  255. counter as string representing the current step of the wizard. (E.g., the
  256. first form is ``'0'`` and the second form is ``'1'``)
  257. .. method:: WizardView.get_form_prefix(step=None, form=None)
  258. Returns the prefix which will be used when calling the form for the given
  259. step. ``step`` contains the step name, ``form`` the form class which will
  260. be called with the returned prefix.
  261. If no ``step`` is given, it will be determined automatically. By default,
  262. this simply uses the step itself and the ``form`` parameter is not used.
  263. For more, see the :ref:`form prefix documentation <form-prefix>`.
  264. .. method:: WizardView.get_form_initial(step)
  265. Returns a dictionary which will be passed as the
  266. :attr:`~django.forms.Form.initial` argument when instantiating the Form
  267. instance for step ``step``. If no initial data was provided while
  268. initializing the form wizard, an empty dictionary should be returned.
  269. The default implementation::
  270. def get_form_initial(self, step):
  271. return self.initial_dict.get(step, {})
  272. .. method:: WizardView.get_form_kwargs(step)
  273. Returns a dictionary which will be used as the keyword arguments when
  274. instantiating the form instance on given ``step``.
  275. The default implementation::
  276. def get_form_kwargs(self, step):
  277. return {}
  278. .. method:: WizardView.get_form_instance(step)
  279. This method will be called only if a :class:`~django.forms.ModelForm` is
  280. used as the form for step ``step``.
  281. Returns an :class:`~django.db.models.Model` object which will be passed as
  282. the ``instance`` argument when instantiating the ``ModelForm`` for step
  283. ``step``. If no instance object was provided while initializing the form
  284. wizard, ``None`` will be returned.
  285. The default implementation::
  286. def get_form_instance(self, step):
  287. return self.instance_dict.get(step, None)
  288. .. method:: WizardView.get_context_data(form, **kwargs)
  289. Returns the template context for a step. You can overwrite this method
  290. to add more data for all or some steps. This method returns a dictionary
  291. containing the rendered form step.
  292. The default template context variables are:
  293. * Any extra data the storage backend has stored
  294. * ``form`` -- form instance of the current step
  295. * ``wizard`` -- the wizard instance itself
  296. Example to add extra variables for a specific step::
  297. def get_context_data(self, form, **kwargs):
  298. context = super(MyWizard, self).get_context_data(form=form, **kwargs)
  299. if self.steps.current == 'my_step_name':
  300. context.update({'another_var': True})
  301. return context
  302. .. method:: WizardView.get_prefix(*args, **kwargs)
  303. This method returns a prefix for use by the storage backends. Backends use
  304. the prefix as a mechanism to allow data to be stored separately for each
  305. wizard. This allows wizards to store their data in a single backend
  306. without overwriting each other.
  307. You can change this method to make the wizard data prefix more unique to,
  308. e.g. have multiple instances of one wizard in one session.
  309. Default implementation::
  310. def get_prefix(self, *args, **kwargs):
  311. # use the lowercase underscore version of the class name
  312. return normalize_name(self.__class__.__name__)
  313. .. method:: WizardView.get_form(step=None, data=None, files=None)
  314. This method constructs the form for a given ``step``. If no ``step`` is
  315. defined, the current step will be determined automatically. If you override
  316. ``get_form``, however, you will need to set ``step`` yourself using
  317. ``self.steps.current`` as in the example below. The method gets three
  318. arguments:
  319. * ``step`` -- The step for which the form instance should be generated.
  320. * ``data`` -- Gets passed to the form's data argument
  321. * ``files`` -- Gets passed to the form's files argument
  322. You can override this method to add extra arguments to the form instance.
  323. Example code to add a user attribute to the form on step 2::
  324. def get_form(self, step=None, data=None, files=None):
  325. form = super(MyWizard, self).get_form(step, data, files)
  326. # determine the step if not given
  327. if step is None:
  328. step = self.steps.current
  329. if step == '1':
  330. form.user = self.request.user
  331. return form
  332. .. method:: WizardView.process_step(form)
  333. Hook for modifying the wizard's internal state, given a fully validated
  334. :class:`~django.forms.Form` object. The Form is guaranteed to have clean,
  335. valid data.
  336. This method gives you a way to post-process the form data before the data
  337. gets stored within the storage backend. By default it just returns the
  338. ``form.data`` dictionary. You should not manipulate the data here but you
  339. can use it to do some extra work if needed (e.g. set storage extra data).
  340. Note that this method is called every time a page is rendered for *all*
  341. submitted steps.
  342. The default implementation::
  343. def process_step(self, form):
  344. return self.get_form_step_data(form)
  345. .. method:: WizardView.process_step_files(form)
  346. This method gives you a way to post-process the form files before the
  347. files gets stored within the storage backend. By default it just returns
  348. the ``form.files`` dictionary. You should not manipulate the data here
  349. but you can use it to do some extra work if needed (e.g. set storage
  350. extra data).
  351. Default implementation::
  352. def process_step_files(self, form):
  353. return self.get_form_step_files(form)
  354. .. method:: WizardView.render_goto_step(step, goto_step, **kwargs)
  355. This method is called when the step should be changed to something else
  356. than the next step. By default, this method just stores the requested
  357. step ``goto_step`` in the storage and then renders the new step.
  358. If you want to store the entered data of the current step before rendering
  359. the next step, you can overwrite this method.
  360. .. method:: WizardView.render_revalidation_failure(step, form, **kwargs)
  361. When the wizard thinks all steps have passed it revalidates all forms with
  362. the data from the backend storage.
  363. If any of the forms don't validate correctly, this method gets called.
  364. This method expects two arguments, ``step`` and ``form``.
  365. The default implementation resets the current step to the first failing
  366. form and redirects the user to the invalid form.
  367. Default implementation::
  368. def render_revalidation_failure(self, step, form, **kwargs):
  369. self.storage.current_step = step
  370. return self.render(form, **kwargs)
  371. .. method:: WizardView.get_form_step_data(form)
  372. This method fetches the data from the ``form`` Form instance and returns the
  373. dictionary. You can use this method to manipulate the values before the data
  374. gets stored in the storage backend.
  375. Default implementation::
  376. def get_form_step_data(self, form):
  377. return form.data
  378. .. method:: WizardView.get_form_step_files(form)
  379. This method returns the form files. You can use this method to manipulate
  380. the files before the data gets stored in the storage backend.
  381. Default implementation::
  382. def get_form_step_files(self, form):
  383. return form.files
  384. .. method:: WizardView.render(form, **kwargs)
  385. This method gets called after the GET or POST request has been handled. You
  386. can hook in this method to, e.g. change the type of HTTP response.
  387. Default implementation::
  388. def render(self, form=None, **kwargs):
  389. form = form or self.get_form()
  390. context = self.get_context_data(form=form, **kwargs)
  391. return self.render_to_response(context)
  392. .. method:: WizardView.get_cleaned_data_for_step(step)
  393. This method returns the cleaned data for a given ``step``. Before returning
  394. the cleaned data, the stored values are revalidated through the form. If
  395. the data doesn't validate, ``None`` will be returned.
  396. .. method:: WizardView.get_all_cleaned_data()
  397. This method returns a merged dictionary of all form steps' ``cleaned_data``
  398. dictionaries. If a step contains a ``FormSet``, the key will be prefixed
  399. with ``formset-`` and contain a list of the formset's ``cleaned_data``
  400. dictionaries. Note that if two or more steps have a field with the same
  401. name, the value for that field from the latest step will overwrite the
  402. value from any earlier steps.
  403. Providing initial data for the forms
  404. ====================================
  405. .. attribute:: WizardView.initial_dict
  406. Initial data for a wizard's :class:`~django.forms.Form` objects can be
  407. provided using the optional :attr:`~WizardView.initial_dict` keyword
  408. argument. This argument should be a dictionary mapping the steps to
  409. dictionaries containing the initial data for each step. The dictionary of
  410. initial data will be passed along to the constructor of the step's
  411. :class:`~django.forms.Form`::
  412. >>> from myapp.forms import ContactForm1, ContactForm2
  413. >>> from myapp.views import ContactWizard
  414. >>> initial = {
  415. ... '0': {'subject': 'Hello', 'sender': 'user@example.com'},
  416. ... '1': {'message': 'Hi there!'}
  417. ... }
  418. >>> # This example is illustrative only and isn't meant to be run in
  419. >>> # the shell since it requires an HttpRequest to pass to the view.
  420. >>> wiz = ContactWizard.as_view([ContactForm1, ContactForm2], initial_dict=initial)(request)
  421. >>> form1 = wiz.get_form('0')
  422. >>> form2 = wiz.get_form('1')
  423. >>> form1.initial
  424. {'sender': 'user@example.com', 'subject': 'Hello'}
  425. >>> form2.initial
  426. {'message': 'Hi there!'}
  427. The ``initial_dict`` can also take a list of dictionaries for a specific
  428. step if the step is a ``FormSet``.
  429. The ``initial_dict`` can also be added as a class attribute named
  430. ``initial_dict`` to avoid having the initial data in the ``urls.py``.
  431. .. _wizard-files:
  432. Handling files
  433. ==============
  434. .. attribute:: WizardView.file_storage
  435. To handle :class:`~django.forms.FileField` within any step form of the wizard,
  436. you have to add a ``file_storage`` to your :class:`WizardView` subclass.
  437. This storage will temporarily store the uploaded files for the wizard. The
  438. ``file_storage`` attribute should be a
  439. :class:`~django.core.files.storage.Storage` subclass.
  440. Django provides a built-in storage class (see :ref:`the built-in filesystem
  441. storage class <builtin-fs-storage>`)::
  442. from django.conf import settings
  443. from django.core.files.storage import FileSystemStorage
  444. class CustomWizardView(WizardView):
  445. ...
  446. file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'photos'))
  447. .. warning::
  448. Please remember to take care of removing old temporary files, as the
  449. :class:`WizardView` will only remove these files if the wizard finishes
  450. correctly.
  451. Conditionally view/skip specific steps
  452. ======================================
  453. .. attribute:: WizardView.condition_dict
  454. The :meth:`~WizardView.as_view` method accepts a ``condition_dict`` argument.
  455. You can pass a dictionary of boolean values or callables. The key should match
  456. the steps names (e.g. '0', '1').
  457. If the value of a specific step is callable it will be called with the
  458. :class:`WizardView` instance as the only argument. If the return value is true,
  459. the step's form will be used.
  460. This example provides a contact form including a condition. The condition is
  461. used to show a message form only if a checkbox in the first step was checked.
  462. The steps are defined in a ``forms.py`` file::
  463. from django import forms
  464. class ContactForm1(forms.Form):
  465. subject = forms.CharField(max_length=100)
  466. sender = forms.EmailField()
  467. leave_message = forms.BooleanField(required=False)
  468. class ContactForm2(forms.Form):
  469. message = forms.CharField(widget=forms.Textarea)
  470. We define our wizard in a ``views.py``::
  471. from django.shortcuts import render_to_response
  472. from django.contrib.formtools.wizard.views import SessionWizardView
  473. def show_message_form_condition(wizard):
  474. # try to get the cleaned data of step 1
  475. cleaned_data = wizard.get_cleaned_data_for_step('0') or {}
  476. # check if the field ``leave_message`` was checked.
  477. return cleaned_data.get('leave_message', True)
  478. class ContactWizard(SessionWizardView):
  479. def done(self, form_list, **kwargs):
  480. return render_to_response('done.html', {
  481. 'form_data': [form.cleaned_data for form in form_list],
  482. })
  483. We need to add the ``ContactWizard`` to our ``urls.py`` file::
  484. from django.conf.urls import url
  485. from myapp.forms import ContactForm1, ContactForm2
  486. from myapp.views import ContactWizard, show_message_form_condition
  487. contact_forms = [ContactForm1, ContactForm2]
  488. urlpatterns = [
  489. url(r'^contact/$', ContactWizard.as_view(contact_forms,
  490. condition_dict={'1': show_message_form_condition}
  491. )),
  492. ]
  493. As you can see, we defined a ``show_message_form_condition`` next to our
  494. :class:`WizardView` subclass and added a ``condition_dict`` argument to the
  495. :meth:`~WizardView.as_view` method. The key refers to the second wizard step
  496. (because of the zero based step index).
  497. How to work with ModelForm and ModelFormSet
  498. ===========================================
  499. .. attribute:: WizardView.instance_dict
  500. WizardView supports :doc:`ModelForms </topics/forms/modelforms>` and
  501. :ref:`ModelFormSets <model-formsets>`. Additionally to
  502. :attr:`~WizardView.initial_dict`, the :meth:`~WizardView.as_view` method takes
  503. an ``instance_dict`` argument that should contain model instances for steps
  504. based on ``ModelForm`` and querysets for steps based on ``ModelFormSet``.
  505. Usage of ``NamedUrlWizardView``
  506. ===============================
  507. .. class:: NamedUrlWizardView
  508. .. class:: NamedUrlSessionWizardView
  509. .. class:: NamedUrlCookieWizardView
  510. There is a :class:`WizardView` subclass which adds named-urls support to the
  511. wizard. By doing this, you can have single urls for every step. You can also
  512. use the :class:`NamedUrlSessionWizardView` or :class:`NamedUrlCookieWizardView`
  513. classes which preselect the backend used for storing information (server-side
  514. sessions and browser cookies respectively).
  515. To use the named urls, you have to change the ``urls.py``.
  516. Below you will see an example of a contact wizard with two steps, step 1 with
  517. ``"contactdata"`` as its name and step 2 with ``"leavemessage"`` as its name.
  518. Additionally you have to pass two more arguments to the
  519. :meth:`~WizardView.as_view` method:
  520. * ``url_name`` -- the name of the url (as provided in the urls.py)
  521. * ``done_step_name`` -- the name in the url for the done step
  522. Example code for the changed ``urls.py`` file::
  523. from django.conf.urls import url
  524. from myapp.forms import ContactForm1, ContactForm2
  525. from myapp.views import ContactWizard
  526. named_contact_forms = (
  527. ('contactdata', ContactForm1),
  528. ('leavemessage', ContactForm2),
  529. )
  530. contact_wizard = ContactWizard.as_view(named_contact_forms,
  531. url_name='contact_step', done_step_name='finished')
  532. urlpatterns = [
  533. url(r'^contact/(?P<step>.+)/$', contact_wizard, name='contact_step'),
  534. url(r'^contact/$', contact_wizard, name='contact'),
  535. ]
  536. Advanced ``NamedUrlWizardView`` methods
  537. =======================================
  538. .. method:: NamedUrlWizardView.get_step_url(step)
  539. This method returns the URL for a specific step.
  540. Default implementation::
  541. def get_step_url(self, step):
  542. return reverse(self.url_name, kwargs={'step': step})