This a wizard tool similar to the one in django.contrib.formtools, but it uses a session. I hope to eventually get this into shape and contribute it to the formtools package, but for right now, here it is.
The wizard steps are broken into 2 categories:
Show Form and Submit Form
Each category has it's own hooks for manipulating the process, for instance you can short-circuit a process_submit_form() and go straight to done() via a return from preprocess_submit_form(). Sorry for the lack of documentation on this.
Here's an example urls.py entry :
(r'^estimate/(?P<page0>\d+)/$', EstimateWizard([EstimateCustomer, EstimateJob, EstimateRoom]))
where EstimateCustomer, Job, and Room are Form classes and EstimateWizard extends SessionFormWizard
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 | class SessionWizard(object):
"""
SessionWizard class -- implements multi-page forms with the following
characteristics:
1) easily supports navigation to arbitrary pages in the wizard
2) uses GETs to display forms (caveat validation errors) and POSTs for
form submissions
Pros are support for back-button and arbitrary navigation within pages
(including the oddity of someone clicking on the refresh button)
The major Con is use of the session scope. In particular, zero
consideration has been given to multipart form data.
"""
def __init__(self, form_list):
"""form_list should be a list of Form classes (not instances)."""
self.base_form_list = form_list[:]
def _init_form_list(self, request):
"""
Copy self.base_form_list to the session scope so that subclasses can
manipulate the form_list for individual users.
"""
form_list_key = self._get_form_list_key()
if form_list_key not in request.session:
request.session[form_list_key] = self.base_form_list[:]
def __call__(self, request, *args, **kwargs):
"""
Initialize the form_list for a session if needed and call GET or
POST depending on the http method.
"""
self._init_form_list(request)
page0 = int(kwargs['page0'])
url_base = self.get_URL_base(request, page0)
if request.method == 'POST':
return self.POST(request, url_base)
else:
return self.GET(request, page0, url_base)
def GET(self, request, page0, url_base):
"""
Display the form/page for the page identified by page0
"""
page_data = self._get_cleaned_data(request.session, page0)
if page_data is None:
form = self._get_form_list(request.session)[page0]()
else:
form_class = self._get_form_list(request.session)[page0]
if issubclass(form_class, forms.ModelForm):
form = form_class(instance=form_class.Meta.model(**page_data))
else:
form = form_class(initial=page_data)
return self._show_form(request, page0, form, url_base)
def POST(self, request, url_base):
"""
Validate form submission, and redirect to GET the next form or return
the response from self.done().
"""
page0 = int(request.POST['page0'])
self._set_POST_data(request.session, request.POST, page0)
form_list = self._get_form_list(request.session)
form = form_list[page0](request.POST)
new_page0 = self.preprocess_submit_form(request, page0, form)
if new_page0 is not None:
return HttpResponseRedirect(url_base + str(new_page0))
else:
if form.is_valid():
self._set_cleaned_data(request.session, page0,
form.cleaned_data)
self._set_page_info(request.session, page0, True)
is_done = self.process_submit_form(request, page0, form)
if (is_done is None or is_done == False) and \
len(form_list) > page0 + 1:
return HttpResponseRedirect(url_base + str(page0 + 1))
else:
first_broken_page, form = \
self._validate_all_forms(request.session)
if first_broken_page is not None:
return self._show_form(request, first_broken_page, form)
else:
return self.done(request)
else:
self._set_page_info(request.session, page0, False)
return self._show_form(request, page0, form)
# form util methods #
def _validate_all_forms(self, session):
"""
Iterate through the session form list and validate based on the POST
data stored in the session for this wizard. Return the page index and
the form of the first invalid form or None, None if all forms are valid.
"""
i = 0
for form_class in self._get_form_list(session):
form = form_class(self._get_POST_data(session, i))
if not form.is_valid():
return i, form
else:
i = i + 1
return None, None
def _show_form(self, request, page0, form, url_base):
"""
Show the form associated with indicated page index.
"""
extra_context = self.process_show_form(request, page0, form)
self._set_current_page(request.session, page0)
page_infos = self._get_page_infos(request.session)
return render_to_response(self.get_template(page0),
{'page0' : page0,
'page' : page0 + 1,
'form' : form,
'page_infos' : page_infos,
'url_base' : url_base,
'extra_context' : extra_context
}, RequestContext(request))
def _get_form_list(self, session):
"""
Return the list of form classes stored in the provided session.
"""
return session[self._get_form_list_key()]
def _insert_form(self, session, page0, form_class):
"""
Insert a form class into the provided session's form list at index
page0.
"""
self._get_form_list(session).insert(page0, form_class)
def _remove_form(self, session, page0):
"""
Remove the form at index page0 from the provided sessions form list.
"""
form_list = self._get_form_list(session)
if len(form_list) > page0:
del form_list[page0]
session[self._get_form_list_key()] = form_list
# end form util methods #
# Form data methods #
def _get_POST_data(self, session, page0):
"""
Return the POST data for a given page index page0, stored in the
provided session.
"""
post_data = self._get_all_POST_data(session)
if len(post_data) > page0:
return post_data[page0]
else:
return {}
def _set_POST_data(self, session, data, page0, force_insert=False):
"""
Set the POST data for a given page index and session to the 'data'
provided. If force_insert is True then the data assignment is forced
as an list.insert(page0, data) call.
"""
post_data = self._get_all_POST_data(session)
if force_insert or len(post_data) <= page0:
post_data.insert(page0, data)
else:
post_data[page0] = data
def _remove_POST_data(self, session, page0):
"""
Remove the POST data stored in the session at index page0.
"""
post_data = self._get_all_POST_data(session)
if len(post_data) > page0:
del post_data[page0]
session[self._get_POST_data_key()] = post_data
def _get_all_POST_data(self, session):
"""
Return the list of all POST data for this wizard from the provided
session.
"""
post_data = []
post_data_key = self._get_POST_data_key()
if post_data_key in session:
post_data = session[post_data_key]
else:
session[post_data_key] = post_data
return post_data
def _get_cleaned_data(self, session, page0):
"""
Return all of cleaned data for this wizard from the provided session.
"""
cleaned_data_key = self._get_cleaned_data_key()
cleaned_data = self._get_all_cleaned_data(session)
if cleaned_data_key in session and len(cleaned_data) > page0:
return cleaned_data[page0]
else:
return {}
def _set_cleaned_data(self, session, page0, data, force_insert=False):
"""
Assign the cleaned data for this wizard in the session at index page0,
optionally forcing a call a list insert call based on the
'force_insert' argument.
"""
cleaned_data = self._get_all_cleaned_data(session)
if force_insert or len(cleaned_data) <= page0:
cleaned_data.insert(page0, data)
else:
cleaned_data[page0] = data
def _get_all_cleaned_data(self, session):
"""
Return a list of all the cleaned data in the session for this wizard.
"""
cleaned_data = []
cleaned_data_key = self._get_cleaned_data_key()
if cleaned_data_key in session:
cleaned_data = session[cleaned_data_key]
else:
session[cleaned_data_key] = cleaned_data
return cleaned_data
def _remove_cleaned_data(self, session, page0):
"""
Remove the cleaned data at index page0 for this wizard from the
provided session.
"""
cleaned_data = self._get_all_cleaned_data(session)
if len(cleaned_data) > page0:
del cleaned_data[page0]
session[self._get_cleaned_data_key()] = cleaned_data
# end Form data methods #
# page methods #
def _set_current_page(self, session, page0):
"""
Iterate through the page info dicts in the session and set
'current_page' to True for the page_info corresponding to page0 and
False for all others.
"""
page_infos = self._get_page_infos(session)
for i in range(len(page_infos)):
if i == page0:
page_infos[i]['current_page'] = True
else:
page_infos[i]['current_page'] = False
def _get_page_infos(self, session):
"""
Return the list of page info dicts stored in the provided session for
this wizard.
"""
page_infos = []
page_info_key = self._get_page_info_key()
if session.has_key(page_info_key):
page_infos = session[page_info_key]
else:
session[page_info_key] = page_infos
return page_infos
def _remove_page(self, session, page0):
"""
Remove the page for this wizard indicated by the page0 argument from
the provided session.
"""
self._remove_form(session, page0)
self._remove_page_info(session, page0)
self._remove_cleaned_data(session, page0)
self._remove_POST_data(session, page0)
def _remove_page_info(self, session, page0):
"""
Remove the page info dict for this wizard stored at the page0 index
from the provided session.
"""
page_infos = self._get_page_infos(session)
if len(page_infos) > page0:
del page_infos[page0]
session[self._get_page_info_key()] = page_infos
def _insert_page(self, session, page0, form_class):
"""
Insert a page into this wizard, storing required session structures.
"""
self._insert_form(session, page0, form_class)
self._set_page_info(session, page0, False, True)
self._set_cleaned_data(session, page0, {}, True)
self._set_POST_data(session, {}, page0, True)
def _set_page_info(self, session, page0, valid, force_insert=False):
"""
Set the page info in this wizard for a page at index page0 and stored
in the provided session.
"""
page_info = {
'valid' : valid,
'title' : self.get_page_title(session, page0)
}
page_infos = self._get_page_infos(session)
if force_insert or len(page_infos) <= page0:
page_infos.insert(page0, page_info)
else:
page_infos[page0] = page_info
self._set_page_infos(session, page_infos)
def _set_page_infos(self, session, page_infos):
"""
Set all the page info dictionaries for this wizard in the provided
session.
"""
session[self._get_page_info_key()] = page_infos
# end page methods #
# Key Methods #
def get_session_key_prefix(self):
"""
Return a session key prefix that will be used to store form and other
wizard data.
"""
return 'session_wizard_data'
def _get_form_list_key(self):
"""
Return a key used to store the list of form classes for this wizard.
"""
return self.get_session_key_prefix() + '-FORM'
def _get_cleaned_data_key(self):
"""
Return a key used to store cleaned data for this wizard.
"""
return self.get_session_key_prefix() + '-CLEANED'
def _get_page_info_key(self):
"""
Return a key used to store page info data for this wizard.
"""
return self.get_session_key_prefix() + '-PAGE_INFO'
def _get_POST_data_key(self):
"""
Return a key used to store POST data for this wizard.
"""
return self.get_session_key_prefix() + '-POST'
# End Key Methods #
# typically overriden methods #
def clear_wizard_from_session(self, session):
"""
Clear the session data used by this wizard from the provided session.
"""
del session[self._get_form_list_key()]
del session[self._get_page_info_key()]
del session[self._get_POST_data_key()]
del session[self._get_cleaned_data_key()]
def get_URL_base(self, request, page0):
"""
Return the URL to this wizard minus the "page0" parto of the URL. This
value is passed to template as url_base.
"""
return request.path.replace("/" + str(page0) + "/", "/")
def get_page_title(self, session, page0):
"""
Return a user friendly title for the page at index page0.
"""
return 'Page %s' % str(page0 + 1)
def process_show_form(self, request, page0, form):
"""
Called before rendering a form either from a GET or when a form submit
is invalid.
"""
def preprocess_submit_form(self, request, page0, form):
"""
Called when a form is POSTed, but before form is validated. If this
function returns None then form submission continues, else it should
return a new page index that will be redirected to as a GET.
"""
def process_submit_form(self, request, page0, form):
"""
Called when a form is POSTed. This is only called if the form data is
valid. If this method returns True, the done() method is called,
otherwise the wizard continues. Note that it is possible that this
method would not return True, and done() would still be called because
there are no more forms left in the form_list.
"""
def get_template(self, page0):
"""
Hook for specifying the name of the template to use for a given page.
Note that this can return a tuple of template names if you'd like to
use the template system's select_template() hook.
"""
return 'forms/session_wizard.html'
def done(self, request):
"""
Hook for doing something with the validated data. This is responsible
for the final processing including clearing the session scope of items
created by this wizard.
"""
raise NotImplementedError("Your %s class has not defined a done() " + \
"method, which is required." \
% self.__class__.__name__)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Please login first before commenting.