2008-08-23 22:25:40 +00:00
|
|
|
===========
|
|
|
|
Form wizard
|
|
|
|
===========
|
|
|
|
|
|
|
|
.. module:: django.contrib.formtools.wizard
|
|
|
|
:synopsis: Splits forms across multiple Web pages.
|
|
|
|
|
|
|
|
Django comes with an optional "form wizard" application that splits
|
2010-08-19 19:27:44 +00:00
|
|
|
:doc:`forms </topics/forms/index>` across multiple Web pages. It maintains
|
2011-02-23 09:41:38 +00:00
|
|
|
state in hashed HTML :samp:`<input type="hidden">` fields so that the full
|
|
|
|
server-side processing can be delayed until the submission of the final form.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
You might want to use this if you have a lengthy form that would be too
|
|
|
|
unwieldy for display on a single page. The first page might ask the user for
|
|
|
|
core information, the second page might ask for less important information,
|
|
|
|
etc.
|
|
|
|
|
|
|
|
The term "wizard," in this context, is `explained on Wikipedia`_.
|
|
|
|
|
|
|
|
.. _explained on Wikipedia: http://en.wikipedia.org/wiki/Wizard_%28software%29
|
|
|
|
.. _forms: ../forms/
|
|
|
|
|
|
|
|
How it works
|
|
|
|
============
|
|
|
|
|
|
|
|
Here's the basic workflow for how a user would use a wizard:
|
|
|
|
|
|
|
|
1. The user visits the first page of the wizard, fills in the form and
|
|
|
|
submits it.
|
|
|
|
2. The server validates the data. If it's invalid, the form is displayed
|
|
|
|
again, with error messages. If it's valid, the server calculates a
|
|
|
|
secure hash of the data and presents the user with the next form,
|
|
|
|
saving the validated data and hash in :samp:`<input type="hidden">`
|
|
|
|
fields.
|
|
|
|
3. Step 1 and 2 repeat, for every subsequent form in the wizard.
|
|
|
|
4. Once the user has submitted all the forms and all the data has been
|
|
|
|
validated, the wizard processes the data -- saving it to the database,
|
2011-04-01 16:10:22 +00:00
|
|
|
sending an email, or whatever the application needs to do.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
Usage
|
|
|
|
=====
|
|
|
|
|
|
|
|
This application handles as much machinery for you as possible. Generally, you
|
|
|
|
just have to do these things:
|
|
|
|
|
2009-12-25 21:07:11 +00:00
|
|
|
1. Define a number of :class:`~django.forms.Form` classes -- one per wizard
|
|
|
|
page.
|
|
|
|
|
|
|
|
2. Create a :class:`FormWizard` class that specifies what to do once all of
|
|
|
|
your forms have been submitted and validated. This also lets you
|
|
|
|
override some of the wizard's behavior.
|
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
3. Create some templates that render the forms. You can define a single,
|
|
|
|
generic template to handle every one of the forms, or you can define a
|
|
|
|
specific template for each form.
|
2009-12-25 21:07:11 +00:00
|
|
|
|
|
|
|
4. Point your URLconf at your :class:`FormWizard` class.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
Defining ``Form`` classes
|
|
|
|
=========================
|
|
|
|
|
2009-12-25 21:07:11 +00:00
|
|
|
The first step in creating a form wizard is to create the
|
|
|
|
:class:`~django.forms.Form` classes. These should be standard
|
2010-08-19 19:27:44 +00:00
|
|
|
:class:`django.forms.Form` classes, covered in the :doc:`forms documentation
|
|
|
|
</topics/forms/index>`. These classes can live anywhere in your codebase, but
|
2009-12-25 21:07:11 +00:00
|
|
|
convention is to put them in a file called :file:`forms.py` in your
|
|
|
|
application.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
For example, let's write a "contact form" wizard, where the first page's form
|
2011-04-01 16:10:22 +00:00
|
|
|
collects the sender's email address and subject, and the second page collects
|
2008-08-23 22:25:40 +00:00
|
|
|
the message itself. Here's what the :file:`forms.py` might look like::
|
|
|
|
|
2009-12-25 21:07:11 +00:00
|
|
|
from django import forms
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
class ContactForm1(forms.Form):
|
|
|
|
subject = forms.CharField(max_length=100)
|
|
|
|
sender = forms.EmailField()
|
|
|
|
|
|
|
|
class ContactForm2(forms.Form):
|
|
|
|
message = forms.CharField(widget=forms.Textarea)
|
|
|
|
|
|
|
|
**Important limitation:** Because the wizard uses HTML hidden fields to store
|
2009-12-25 21:07:11 +00:00
|
|
|
data between pages, you may not include a :class:`~django.forms.FileField`
|
2008-08-23 22:25:40 +00:00
|
|
|
in any form except the last one.
|
|
|
|
|
|
|
|
Creating a ``FormWizard`` class
|
|
|
|
===============================
|
|
|
|
|
2009-12-25 21:07:11 +00:00
|
|
|
The next step is to create a
|
|
|
|
:class:`django.contrib.formtools.wizard.FormWizard` subclass. As with your
|
|
|
|
:class:`~django.forms.Form` classes, this :class:`FormWizard` class can live
|
|
|
|
anywhere in your codebase, but convention is to put it in :file:`forms.py`.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
The only requirement on this subclass is that it implement a
|
2009-12-25 21:07:11 +00:00
|
|
|
:meth:`~FormWizard.done()` method.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
2009-12-25 21:07:11 +00:00
|
|
|
.. method:: FormWizard.done
|
|
|
|
|
|
|
|
This method specifies what should happen when the data for *every* form is
|
|
|
|
submitted and validated. This method is passed two arguments:
|
|
|
|
|
|
|
|
* ``request`` -- an :class:`~django.http.HttpRequest` object
|
|
|
|
* ``form_list`` -- a list of :class:`~django.forms.Form` classes
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
In this simplistic example, rather than perform any database operation, the
|
|
|
|
method simply renders a template of the validated data::
|
|
|
|
|
|
|
|
from django.shortcuts import render_to_response
|
|
|
|
from django.contrib.formtools.wizard import FormWizard
|
|
|
|
|
|
|
|
class ContactWizard(FormWizard):
|
|
|
|
def done(self, request, form_list):
|
|
|
|
return render_to_response('done.html', {
|
|
|
|
'form_data': [form.cleaned_data for form in form_list],
|
|
|
|
})
|
|
|
|
|
|
|
|
Note that this method will be called via ``POST``, so it really ought to be a
|
|
|
|
good Web citizen and redirect after processing the data. Here's another
|
|
|
|
example::
|
|
|
|
|
|
|
|
from django.http import HttpResponseRedirect
|
|
|
|
from django.contrib.formtools.wizard import FormWizard
|
|
|
|
|
|
|
|
class ContactWizard(FormWizard):
|
|
|
|
def done(self, request, form_list):
|
|
|
|
do_something_with_the_form_data(form_list)
|
|
|
|
return HttpResponseRedirect('/page-to-redirect-to-when-done/')
|
|
|
|
|
|
|
|
See the section `Advanced FormWizard methods`_ below to learn about more
|
2009-12-25 21:07:11 +00:00
|
|
|
:class:`FormWizard` hooks.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
Creating templates for the forms
|
|
|
|
================================
|
|
|
|
|
|
|
|
Next, you'll need to create a template that renders the wizard's forms. By
|
|
|
|
default, every form uses a template called :file:`forms/wizard.html`. (You can
|
2009-12-25 21:07:11 +00:00
|
|
|
change this template name by overriding :meth:`~FormWizard.get_template()`,
|
|
|
|
which is documented below. This hook also allows you to use a different
|
|
|
|
template for each form.)
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
This template expects the following context:
|
|
|
|
|
|
|
|
* ``step_field`` -- The name of the hidden field containing the step.
|
|
|
|
* ``step0`` -- The current step (zero-based).
|
|
|
|
* ``step`` -- The current step (one-based).
|
|
|
|
* ``step_count`` -- The total number of steps.
|
2009-12-25 21:07:11 +00:00
|
|
|
* ``form`` -- The :class:`~django.forms.Form` instance for the current step
|
|
|
|
(either empty or with errors).
|
2008-08-23 22:25:40 +00:00
|
|
|
* ``previous_fields`` -- A string representing every previous data field,
|
|
|
|
plus hashes for completed forms, all in the form of hidden fields. Note
|
2009-12-25 21:07:11 +00:00
|
|
|
that you'll need to run this through the :tfilter:`safe` template filter,
|
|
|
|
to prevent auto-escaping, because it's raw HTML.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
2009-12-25 21:07:11 +00:00
|
|
|
You can supply extra context to this template in two ways:
|
2008-08-23 22:25:40 +00:00
|
|
|
|
2009-12-25 21:07:11 +00:00
|
|
|
* Set the :attr:`~FormWizard.extra_context` attribute on your
|
|
|
|
:class:`FormWizard` subclass to a dictionary.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
2009-12-25 21:07:11 +00:00
|
|
|
* Pass a dictionary as a parameter named ``extra_context`` to your wizard's
|
|
|
|
URL pattern in your URLconf. See :ref:`hooking-wizard-into-urlconf`.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
2008-09-09 01:54:20 +00:00
|
|
|
Here's a full example template:
|
|
|
|
|
|
|
|
.. code-block:: html+django
|
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
{% extends "base.html" %}
|
|
|
|
|
|
|
|
{% block content %}
|
|
|
|
<p>Step {{ step }} of {{ step_count }}</p>
|
Fixed #9977 - CsrfMiddleware gets template tag added, session dependency removed, and turned on by default.
This is a large change to CSRF protection for Django. It includes:
* removing the dependency on the session framework.
* deprecating CsrfResponseMiddleware, and replacing with a core template tag.
* turning on CSRF protection by default by adding CsrfViewMiddleware to
the default value of MIDDLEWARE_CLASSES.
* protecting all contrib apps (whatever is in settings.py)
using a decorator.
For existing users of the CSRF functionality, it should be a seamless update,
but please note that it includes DEPRECATION of features in Django 1.1,
and there are upgrade steps which are detailed in the docs.
Many thanks to 'Glenn' and 'bthomas', who did a lot of the thinking and work
on the patch, and to lots of other people including Simon Willison and
Russell Keith-Magee who refined the ideas.
Details of the rationale for these changes is found here:
http://code.djangoproject.com/wiki/CsrfProtection
As of this commit, the CSRF code is mainly in 'contrib'. The code will be
moved to core in a separate commit, to make the changeset as readable as
possible.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@11660 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-10-26 23:23:07 +00:00
|
|
|
<form action="." method="post">{% csrf_token %}
|
2008-08-23 22:25:40 +00:00
|
|
|
<table>
|
|
|
|
{{ form }}
|
|
|
|
</table>
|
|
|
|
<input type="hidden" name="{{ step_field }}" value="{{ step0 }}" />
|
|
|
|
{{ previous_fields|safe }}
|
|
|
|
<input type="submit">
|
|
|
|
</form>
|
|
|
|
{% endblock %}
|
|
|
|
|
|
|
|
Note that ``previous_fields``, ``step_field`` and ``step0`` are all required
|
|
|
|
for the wizard to work properly.
|
|
|
|
|
2009-12-25 21:07:11 +00:00
|
|
|
.. _hooking-wizard-into-urlconf:
|
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
Hooking the wizard into a URLconf
|
|
|
|
=================================
|
|
|
|
|
2010-08-07 07:57:35 +00:00
|
|
|
Finally, we need to specify which forms to use in the wizard, and then
|
|
|
|
deploy the new :class:`FormWizard` object a URL in ``urls.py``. The
|
|
|
|
wizard takes a list of your :class:`~django.forms.Form` objects as
|
|
|
|
arguments when you instantiate the Wizard::
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
from django.conf.urls.defaults import *
|
2010-10-19 00:10:22 +00:00
|
|
|
from testapp.forms import ContactForm1, ContactForm2, ContactWizard
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
urlpatterns = patterns('',
|
|
|
|
(r'^contact/$', ContactWizard([ContactForm1, ContactForm2])),
|
|
|
|
)
|
|
|
|
|
2010-02-22 05:00:36 +00:00
|
|
|
Advanced ``FormWizard`` methods
|
|
|
|
===============================
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
.. class:: FormWizard
|
|
|
|
|
2009-12-25 21:07:11 +00:00
|
|
|
Aside from the :meth:`~done()` method, :class:`FormWizard` offers a few
|
2008-08-23 22:25:40 +00:00
|
|
|
advanced method hooks that let you customize how your wizard works.
|
|
|
|
|
2009-12-25 21:07:11 +00:00
|
|
|
Some of these methods take an argument ``step``, which is a zero-based
|
|
|
|
counter representing the current step of the wizard. (E.g., the first form
|
|
|
|
is ``0`` and the second form is ``1``.)
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
.. method:: FormWizard.prefix_for_step
|
|
|
|
|
2009-12-25 21:07:11 +00:00
|
|
|
Given the step, returns a form prefix to use. By default, this simply uses
|
|
|
|
the step itself. For more, see the :ref:`form prefix documentation
|
|
|
|
<form-prefix>`.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
Default implementation::
|
|
|
|
|
|
|
|
def prefix_for_step(self, step):
|
|
|
|
return str(step)
|
|
|
|
|
|
|
|
.. method:: FormWizard.render_hash_failure
|
|
|
|
|
|
|
|
Renders a template if the hash check fails. It's rare that you'd need to
|
|
|
|
override this.
|
|
|
|
|
|
|
|
Default implementation::
|
|
|
|
|
|
|
|
def render_hash_failure(self, request, step):
|
|
|
|
return self.render(self.get_form(step), request, step,
|
2009-12-25 21:07:11 +00:00
|
|
|
context={'wizard_error':
|
|
|
|
'We apologize, but your form has expired. Please'
|
|
|
|
' continue filling out the form from this page.'})
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
.. method:: FormWizard.security_hash
|
|
|
|
|
2009-12-25 21:07:11 +00:00
|
|
|
Calculates the security hash for the given request object and
|
|
|
|
:class:`~django.forms.Form` instance.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
Fixed #14445 - Use HMAC and constant-time comparison functions where needed.
All adhoc MAC applications have been updated to use HMAC, using SHA1 to
generate unique keys for each application based on the SECRET_KEY, which is
common practice for this situation. In all cases, backwards compatibility
with existing hashes has been maintained, aiming to phase this out as per
the normal deprecation process. In this way, under most normal
circumstances the old hashes will have expired (e.g. by session expiration
etc.) before they become invalid.
In the case of the messages framework and the cookie backend, which was
already using HMAC, there is the possibility of a backwards incompatibility
if the SECRET_KEY is shorter than the default 50 bytes, but the low
likelihood and low impact meant compatibility code was not worth it.
All known instances where tokens/hashes were compared using simple string
equality, which could potentially open timing based attacks, have also been
fixed using a constant-time comparison function.
There are no known practical attacks against the existing implementations,
so these security improvements will not be backported.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@14218 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2010-10-14 20:54:30 +00:00
|
|
|
By default, this generates a SHA1 HMAC using your form data and your
|
2009-12-25 21:07:11 +00:00
|
|
|
:setting:`SECRET_KEY` setting. It's rare that somebody would need to
|
|
|
|
override this.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
Example::
|
|
|
|
|
|
|
|
def security_hash(self, request, form):
|
|
|
|
return my_hash_function(request, form)
|
|
|
|
|
|
|
|
.. method:: FormWizard.parse_params
|
|
|
|
|
2009-12-25 21:07:11 +00:00
|
|
|
A hook for saving state from the request object and ``args`` / ``kwargs``
|
|
|
|
that were captured from the URL by your URLconf.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
By default, this does nothing.
|
|
|
|
|
|
|
|
Example::
|
|
|
|
|
|
|
|
def parse_params(self, request, *args, **kwargs):
|
|
|
|
self.my_state = args[0]
|
|
|
|
|
|
|
|
.. method:: FormWizard.get_template
|
|
|
|
|
|
|
|
Returns the name of the template that should be used for the given step.
|
|
|
|
|
|
|
|
By default, this returns :file:`'forms/wizard.html'`, regardless of step.
|
|
|
|
|
|
|
|
Example::
|
|
|
|
|
|
|
|
def get_template(self, step):
|
|
|
|
return 'myapp/wizard_%s.html' % step
|
|
|
|
|
2009-12-25 21:07:11 +00:00
|
|
|
If :meth:`~FormWizard.get_template` returns a list of strings, then the
|
|
|
|
wizard will use the template system's
|
|
|
|
:func:`~django.template.loader.select_template` function.
|
2008-08-23 22:25:40 +00:00
|
|
|
This means the system will use the first template that exists on the
|
|
|
|
filesystem. For example::
|
|
|
|
|
|
|
|
def get_template(self, step):
|
|
|
|
return ['myapp/wizard_%s.html' % step, 'myapp/wizard.html']
|
|
|
|
|
|
|
|
.. method:: FormWizard.render_template
|
|
|
|
|
|
|
|
Renders the template for the given step, returning an
|
2009-03-31 23:34:03 +00:00
|
|
|
:class:`~django.http.HttpResponse` object.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
2009-12-25 21:07:11 +00:00
|
|
|
Override this method if you want to add a custom context, return a
|
|
|
|
different MIME type, etc. If you only need to override the template name,
|
|
|
|
use :meth:`~FormWizard.get_template` instead.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
The template will be rendered with the context documented in the
|
|
|
|
"Creating templates for the forms" section above.
|
|
|
|
|
|
|
|
.. method:: FormWizard.process_step
|
|
|
|
|
|
|
|
Hook for modifying the wizard's internal state, given a fully validated
|
2009-12-25 21:07:11 +00:00
|
|
|
:class:`~django.forms.Form` object. The Form is guaranteed to have clean,
|
|
|
|
valid data.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
2009-12-25 21:07:11 +00:00
|
|
|
This method should *not* modify any of that data. Rather, it might want to
|
|
|
|
set ``self.extra_context`` or dynamically alter ``self.form_list``, based
|
|
|
|
on previously submitted forms.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
Note that this method is called every time a page is rendered for *all*
|
|
|
|
submitted steps.
|
|
|
|
|
|
|
|
The function signature::
|
|
|
|
|
|
|
|
def process_step(self, request, form, step):
|
|
|
|
# ...
|
2011-05-15 19:11:57 +00:00
|
|
|
|
|
|
|
Providing initial data for the forms
|
|
|
|
====================================
|
|
|
|
|
|
|
|
.. attribute:: FormWizard.initial
|
|
|
|
|
|
|
|
Initial data for a wizard's :class:`~django.forms.Form` objects can be
|
|
|
|
provided using the optional :attr:`~FormWizard.initial` keyword argument.
|
|
|
|
This argument should be a dictionary mapping a step to a dictionary
|
|
|
|
containing the initial data for that step. The dictionary of initial data
|
|
|
|
will be passed along to the constructor of the step's
|
|
|
|
:class:`~django.forms.Form`::
|
|
|
|
|
|
|
|
>>> from testapp.forms import ContactForm1, ContactForm2, ContactWizard
|
|
|
|
>>> initial = {
|
|
|
|
... 0: {'subject': 'Hello', 'sender': 'user@example.com'},
|
|
|
|
... 1: {'message': 'Hi there!'}
|
|
|
|
... }
|
|
|
|
>>> wiz = ContactWizard([ContactForm1, ContactForm2], initial=initial)
|
|
|
|
>>> form1 = wiz.get_form(0)
|
|
|
|
>>> form2 = wiz.get_form(1)
|
|
|
|
>>> form1.initial
|
|
|
|
{'sender': 'user@example.com', 'subject': 'Hello'}
|
|
|
|
>>> form2.initial
|
|
|
|
{'message': 'Hi there!'}
|