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