views.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  1. import re
  2. from django import forms
  3. from django.shortcuts import redirect
  4. from django.core.urlresolvers import reverse
  5. from django.forms import formsets, ValidationError
  6. from django.views.generic import TemplateView
  7. from django.utils.datastructures import SortedDict
  8. from django.utils.decorators import classonlymethod
  9. from django.utils.translation import ugettext as _
  10. from django.utils import six
  11. from django.contrib.formtools.wizard.storage import get_storage
  12. from django.contrib.formtools.wizard.storage.exceptions import NoFileStorageConfigured
  13. from django.contrib.formtools.wizard.forms import ManagementForm
  14. def normalize_name(name):
  15. """
  16. Converts camel-case style names into underscore separated words. Example::
  17. >>> normalize_name('oneTwoThree')
  18. 'one_two_three'
  19. >>> normalize_name('FourFiveSix')
  20. 'four_five_six'
  21. """
  22. new = re.sub('(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))', '_\\1', name)
  23. return new.lower().strip('_')
  24. class StepsHelper(object):
  25. def __init__(self, wizard):
  26. self._wizard = wizard
  27. def __dir__(self):
  28. return self.all
  29. def __len__(self):
  30. return self.count
  31. def __repr__(self):
  32. return '<StepsHelper for %s (steps: %s)>' % (self._wizard, self.all)
  33. @property
  34. def all(self):
  35. "Returns the names of all steps/forms."
  36. return list(self._wizard.get_form_list())
  37. @property
  38. def count(self):
  39. "Returns the total number of steps/forms in this the wizard."
  40. return len(self.all)
  41. @property
  42. def current(self):
  43. """
  44. Returns the current step. If no current step is stored in the
  45. storage backend, the first step will be returned.
  46. """
  47. return self._wizard.storage.current_step or self.first
  48. @property
  49. def first(self):
  50. "Returns the name of the first step."
  51. return self.all[0]
  52. @property
  53. def last(self):
  54. "Returns the name of the last step."
  55. return self.all[-1]
  56. @property
  57. def next(self):
  58. "Returns the next step."
  59. return self._wizard.get_next_step()
  60. @property
  61. def prev(self):
  62. "Returns the previous step."
  63. return self._wizard.get_prev_step()
  64. @property
  65. def index(self):
  66. "Returns the index for the current step."
  67. return self._wizard.get_step_index()
  68. @property
  69. def step0(self):
  70. return int(self.index)
  71. @property
  72. def step1(self):
  73. return int(self.index) + 1
  74. class WizardView(TemplateView):
  75. """
  76. The WizardView is used to create multi-page forms and handles all the
  77. storage and validation stuff. The wizard is based on Django's generic
  78. class based views.
  79. """
  80. storage_name = None
  81. form_list = None
  82. initial_dict = None
  83. instance_dict = None
  84. condition_dict = None
  85. template_name = 'formtools/wizard/wizard_form.html'
  86. def __repr__(self):
  87. return '<%s: forms: %s>' % (self.__class__.__name__, self.form_list)
  88. @classonlymethod
  89. def as_view(cls, *args, **kwargs):
  90. """
  91. This method is used within urls.py to create unique wizardview
  92. instances for every request. We need to override this method because
  93. we add some kwargs which are needed to make the wizardview usable.
  94. """
  95. initkwargs = cls.get_initkwargs(*args, **kwargs)
  96. return super(WizardView, cls).as_view(**initkwargs)
  97. @classmethod
  98. def get_initkwargs(cls, form_list=None, initial_dict=None,
  99. instance_dict=None, condition_dict=None, *args, **kwargs):
  100. """
  101. Creates a dict with all needed parameters for the form wizard instances.
  102. * `form_list` - is a list of forms. The list entries can be single form
  103. classes or tuples of (`step_name`, `form_class`). If you pass a list
  104. of forms, the wizardview will convert the class list to
  105. (`zero_based_counter`, `form_class`). This is needed to access the
  106. form for a specific step.
  107. * `initial_dict` - contains a dictionary of initial data dictionaries.
  108. The key should be equal to the `step_name` in the `form_list` (or
  109. the str of the zero based counter - if no step_names added in the
  110. `form_list`)
  111. * `instance_dict` - contains a dictionary whose values are model
  112. instances if the step is based on a ``ModelForm`` and querysets if
  113. the step is based on a ``ModelFormSet``. The key should be equal to
  114. the `step_name` in the `form_list`. Same rules as for `initial_dict`
  115. apply.
  116. * `condition_dict` - contains a dictionary of boolean values or
  117. callables. If the value of for a specific `step_name` is callable it
  118. will be called with the wizardview instance as the only argument.
  119. If the return value is true, the step's form will be used.
  120. """
  121. kwargs.update({
  122. 'initial_dict': initial_dict or kwargs.pop('initial_dict',
  123. getattr(cls, 'initial_dict', None)) or {},
  124. 'instance_dict': instance_dict or kwargs.pop('instance_dict',
  125. getattr(cls, 'instance_dict', None)) or {},
  126. 'condition_dict': condition_dict or kwargs.pop('condition_dict',
  127. getattr(cls, 'condition_dict', None)) or {}
  128. })
  129. form_list = form_list or kwargs.pop('form_list',
  130. getattr(cls, 'form_list', None)) or []
  131. computed_form_list = SortedDict()
  132. assert len(form_list) > 0, 'at least one form is needed'
  133. # walk through the passed form list
  134. for i, form in enumerate(form_list):
  135. if isinstance(form, (list, tuple)):
  136. # if the element is a tuple, add the tuple to the new created
  137. # sorted dictionary.
  138. computed_form_list[six.text_type(form[0])] = form[1]
  139. else:
  140. # if not, add the form with a zero based counter as unicode
  141. computed_form_list[six.text_type(i)] = form
  142. # walk through the new created list of forms
  143. for form in six.itervalues(computed_form_list):
  144. if issubclass(form, formsets.BaseFormSet):
  145. # if the element is based on BaseFormSet (FormSet/ModelFormSet)
  146. # we need to override the form variable.
  147. form = form.form
  148. # check if any form contains a FileField, if yes, we need a
  149. # file_storage added to the wizardview (by subclassing).
  150. for field in six.itervalues(form.base_fields):
  151. if (isinstance(field, forms.FileField) and
  152. not hasattr(cls, 'file_storage')):
  153. raise NoFileStorageConfigured(
  154. "You need to define 'file_storage' in your "
  155. "wizard view in order to handle file uploads.")
  156. # build the kwargs for the wizardview instances
  157. kwargs['form_list'] = computed_form_list
  158. return kwargs
  159. def get_prefix(self, *args, **kwargs):
  160. # TODO: Add some kind of unique id to prefix
  161. return normalize_name(self.__class__.__name__)
  162. def get_form_list(self):
  163. """
  164. This method returns a form_list based on the initial form list but
  165. checks if there is a condition method/value in the condition_list.
  166. If an entry exists in the condition list, it will call/read the value
  167. and respect the result. (True means add the form, False means ignore
  168. the form)
  169. The form_list is always generated on the fly because condition methods
  170. could use data from other (maybe previous forms).
  171. """
  172. form_list = SortedDict()
  173. for form_key, form_class in six.iteritems(self.form_list):
  174. # try to fetch the value from condition list, by default, the form
  175. # gets passed to the new list.
  176. condition = self.condition_dict.get(form_key, True)
  177. if callable(condition):
  178. # call the value if needed, passes the current instance.
  179. condition = condition(self)
  180. if condition:
  181. form_list[form_key] = form_class
  182. return form_list
  183. def dispatch(self, request, *args, **kwargs):
  184. """
  185. This method gets called by the routing engine. The first argument is
  186. `request` which contains a `HttpRequest` instance.
  187. The request is stored in `self.request` for later use. The storage
  188. instance is stored in `self.storage`.
  189. After processing the request using the `dispatch` method, the
  190. response gets updated by the storage engine (for example add cookies).
  191. """
  192. # add the storage engine to the current wizardview instance
  193. self.prefix = self.get_prefix(*args, **kwargs)
  194. self.storage = get_storage(self.storage_name, self.prefix, request,
  195. getattr(self, 'file_storage', None))
  196. self.steps = StepsHelper(self)
  197. response = super(WizardView, self).dispatch(request, *args, **kwargs)
  198. # update the response (e.g. adding cookies)
  199. self.storage.update_response(response)
  200. return response
  201. def get(self, request, *args, **kwargs):
  202. """
  203. This method handles GET requests.
  204. If a GET request reaches this point, the wizard assumes that the user
  205. just starts at the first step or wants to restart the process.
  206. The data of the wizard will be resetted before rendering the first step.
  207. """
  208. self.storage.reset()
  209. # reset the current step to the first step.
  210. self.storage.current_step = self.steps.first
  211. return self.render(self.get_form())
  212. def post(self, *args, **kwargs):
  213. """
  214. This method handles POST requests.
  215. The wizard will render either the current step (if form validation
  216. wasn't successful), the next step (if the current step was stored
  217. successful) or the done view (if no more steps are available)
  218. """
  219. # Look for a wizard_goto_step element in the posted data which
  220. # contains a valid step name. If one was found, render the requested
  221. # form. (This makes stepping back a lot easier).
  222. wizard_goto_step = self.request.POST.get('wizard_goto_step', None)
  223. if wizard_goto_step and wizard_goto_step in self.get_form_list():
  224. return self.render_goto_step(wizard_goto_step)
  225. # Check if form was refreshed
  226. management_form = ManagementForm(self.request.POST, prefix=self.prefix)
  227. if not management_form.is_valid():
  228. raise ValidationError(
  229. _('ManagementForm data is missing or has been tampered.'),
  230. code='missing_management_form',
  231. )
  232. form_current_step = management_form.cleaned_data['current_step']
  233. if (form_current_step != self.steps.current and
  234. self.storage.current_step is not None):
  235. # form refreshed, change current step
  236. self.storage.current_step = form_current_step
  237. # get the form for the current step
  238. form = self.get_form(data=self.request.POST, files=self.request.FILES)
  239. # and try to validate
  240. if form.is_valid():
  241. # if the form is valid, store the cleaned data and files.
  242. self.storage.set_step_data(self.steps.current, self.process_step(form))
  243. self.storage.set_step_files(self.steps.current, self.process_step_files(form))
  244. # check if the current step is the last step
  245. if self.steps.current == self.steps.last:
  246. # no more steps, render done view
  247. return self.render_done(form, **kwargs)
  248. else:
  249. # proceed to the next step
  250. return self.render_next_step(form)
  251. return self.render(form)
  252. def render_next_step(self, form, **kwargs):
  253. """
  254. This method gets called when the next step/form should be rendered.
  255. `form` contains the last/current form.
  256. """
  257. # get the form instance based on the data from the storage backend
  258. # (if available).
  259. next_step = self.steps.next
  260. new_form = self.get_form(next_step,
  261. data=self.storage.get_step_data(next_step),
  262. files=self.storage.get_step_files(next_step))
  263. # change the stored current step
  264. self.storage.current_step = next_step
  265. return self.render(new_form, **kwargs)
  266. def render_goto_step(self, goto_step, **kwargs):
  267. """
  268. This method gets called when the current step has to be changed.
  269. `goto_step` contains the requested step to go to.
  270. """
  271. self.storage.current_step = goto_step
  272. form = self.get_form(
  273. data=self.storage.get_step_data(self.steps.current),
  274. files=self.storage.get_step_files(self.steps.current))
  275. return self.render(form)
  276. def render_done(self, form, **kwargs):
  277. """
  278. This method gets called when all forms passed. The method should also
  279. re-validate all steps to prevent manipulation. If any form don't
  280. validate, `render_revalidation_failure` should get called.
  281. If everything is fine call `done`.
  282. """
  283. final_form_list = []
  284. # walk through the form list and try to validate the data again.
  285. for form_key in self.get_form_list():
  286. form_obj = self.get_form(step=form_key,
  287. data=self.storage.get_step_data(form_key),
  288. files=self.storage.get_step_files(form_key))
  289. if not form_obj.is_valid():
  290. return self.render_revalidation_failure(form_key, form_obj, **kwargs)
  291. final_form_list.append(form_obj)
  292. # render the done view and reset the wizard before returning the
  293. # response. This is needed to prevent from rendering done with the
  294. # same data twice.
  295. done_response = self.done(final_form_list, **kwargs)
  296. self.storage.reset()
  297. return done_response
  298. def get_form_prefix(self, step=None, form=None):
  299. """
  300. Returns the prefix which will be used when calling the actual form for
  301. the given step. `step` contains the step-name, `form` the form which
  302. will be called with the returned prefix.
  303. If no step is given, the form_prefix will determine the current step
  304. automatically.
  305. """
  306. if step is None:
  307. step = self.steps.current
  308. return str(step)
  309. def get_form_initial(self, step):
  310. """
  311. Returns a dictionary which will be passed to the form for `step`
  312. as `initial`. If no initial data was provied while initializing the
  313. form wizard, a empty dictionary will be returned.
  314. """
  315. return self.initial_dict.get(step, {})
  316. def get_form_instance(self, step):
  317. """
  318. Returns a object which will be passed to the form for `step`
  319. as `instance`. If no instance object was provied while initializing
  320. the form wizard, None will be returned.
  321. """
  322. return self.instance_dict.get(step, None)
  323. def get_form_kwargs(self, step=None):
  324. """
  325. Returns the keyword arguments for instantiating the form
  326. (or formset) on the given step.
  327. """
  328. return {}
  329. def get_form(self, step=None, data=None, files=None):
  330. """
  331. Constructs the form for a given `step`. If no `step` is defined, the
  332. current step will be determined automatically.
  333. The form will be initialized using the `data` argument to prefill the
  334. new form. If needed, instance or queryset (for `ModelForm` or
  335. `ModelFormSet`) will be added too.
  336. """
  337. if step is None:
  338. step = self.steps.current
  339. # prepare the kwargs for the form instance.
  340. kwargs = self.get_form_kwargs(step)
  341. kwargs.update({
  342. 'data': data,
  343. 'files': files,
  344. 'prefix': self.get_form_prefix(step, self.form_list[step]),
  345. 'initial': self.get_form_initial(step),
  346. })
  347. if issubclass(self.form_list[step], forms.ModelForm):
  348. # If the form is based on ModelForm, add instance if available
  349. # and not previously set.
  350. kwargs.setdefault('instance', self.get_form_instance(step))
  351. elif issubclass(self.form_list[step], forms.models.BaseModelFormSet):
  352. # If the form is based on ModelFormSet, add queryset if available
  353. # and not previous set.
  354. kwargs.setdefault('queryset', self.get_form_instance(step))
  355. return self.form_list[step](**kwargs)
  356. def process_step(self, form):
  357. """
  358. This method is used to postprocess the form data. By default, it
  359. returns the raw `form.data` dictionary.
  360. """
  361. return self.get_form_step_data(form)
  362. def process_step_files(self, form):
  363. """
  364. This method is used to postprocess the form files. By default, it
  365. returns the raw `form.files` dictionary.
  366. """
  367. return self.get_form_step_files(form)
  368. def render_revalidation_failure(self, step, form, **kwargs):
  369. """
  370. Gets called when a form doesn't validate when rendering the done
  371. view. By default, it changes the current step to failing forms step
  372. and renders the form.
  373. """
  374. self.storage.current_step = step
  375. return self.render(form, **kwargs)
  376. def get_form_step_data(self, form):
  377. """
  378. Is used to return the raw form data. You may use this method to
  379. manipulate the data.
  380. """
  381. return form.data
  382. def get_form_step_files(self, form):
  383. """
  384. Is used to return the raw form files. You may use this method to
  385. manipulate the data.
  386. """
  387. return form.files
  388. def get_all_cleaned_data(self):
  389. """
  390. Returns a merged dictionary of all step cleaned_data dictionaries.
  391. If a step contains a `FormSet`, the key will be prefixed with
  392. 'formset-' and contain a list of the formset cleaned_data dictionaries.
  393. """
  394. cleaned_data = {}
  395. for form_key in self.get_form_list():
  396. form_obj = self.get_form(
  397. step=form_key,
  398. data=self.storage.get_step_data(form_key),
  399. files=self.storage.get_step_files(form_key)
  400. )
  401. if form_obj.is_valid():
  402. if isinstance(form_obj.cleaned_data, (tuple, list)):
  403. cleaned_data.update({
  404. 'formset-%s' % form_key: form_obj.cleaned_data
  405. })
  406. else:
  407. cleaned_data.update(form_obj.cleaned_data)
  408. return cleaned_data
  409. def get_cleaned_data_for_step(self, step):
  410. """
  411. Returns the cleaned data for a given `step`. Before returning the
  412. cleaned data, the stored values are revalidated through the form.
  413. If the data doesn't validate, None will be returned.
  414. """
  415. if step in self.form_list:
  416. form_obj = self.get_form(step=step,
  417. data=self.storage.get_step_data(step),
  418. files=self.storage.get_step_files(step))
  419. if form_obj.is_valid():
  420. return form_obj.cleaned_data
  421. return None
  422. def get_next_step(self, step=None):
  423. """
  424. Returns the next step after the given `step`. If no more steps are
  425. available, None will be returned. If the `step` argument is None, the
  426. current step will be determined automatically.
  427. """
  428. if step is None:
  429. step = self.steps.current
  430. form_list = self.get_form_list()
  431. key = form_list.keyOrder.index(step) + 1
  432. if len(form_list.keyOrder) > key:
  433. return form_list.keyOrder[key]
  434. return None
  435. def get_prev_step(self, step=None):
  436. """
  437. Returns the previous step before the given `step`. If there are no
  438. steps available, None will be returned. If the `step` argument is
  439. None, the current step will be determined automatically.
  440. """
  441. if step is None:
  442. step = self.steps.current
  443. form_list = self.get_form_list()
  444. key = form_list.keyOrder.index(step) - 1
  445. if key >= 0:
  446. return form_list.keyOrder[key]
  447. return None
  448. def get_step_index(self, step=None):
  449. """
  450. Returns the index for the given `step` name. If no step is given,
  451. the current step will be used to get the index.
  452. """
  453. if step is None:
  454. step = self.steps.current
  455. return self.get_form_list().keyOrder.index(step)
  456. def get_context_data(self, form, **kwargs):
  457. """
  458. Returns the template context for a step. You can overwrite this method
  459. to add more data for all or some steps. This method returns a
  460. dictionary containing the rendered form step. Available template
  461. context variables are:
  462. * all extra data stored in the storage backend
  463. * `form` - form instance of the current step
  464. * `wizard` - the wizard instance itself
  465. Example:
  466. .. code-block:: python
  467. class MyWizard(WizardView):
  468. def get_context_data(self, form, **kwargs):
  469. context = super(MyWizard, self).get_context_data(form=form, **kwargs)
  470. if self.steps.current == 'my_step_name':
  471. context.update({'another_var': True})
  472. return context
  473. """
  474. context = super(WizardView, self).get_context_data(form=form, **kwargs)
  475. context.update(self.storage.extra_data)
  476. context['wizard'] = {
  477. 'form': form,
  478. 'steps': self.steps,
  479. 'management_form': ManagementForm(prefix=self.prefix, initial={
  480. 'current_step': self.steps.current,
  481. }),
  482. }
  483. return context
  484. def render(self, form=None, **kwargs):
  485. """
  486. Returns a ``HttpResponse`` containing all needed context data.
  487. """
  488. form = form or self.get_form()
  489. context = self.get_context_data(form=form, **kwargs)
  490. return self.render_to_response(context)
  491. def done(self, form_list, **kwargs):
  492. """
  493. This method must be overridden by a subclass to process to form data
  494. after processing all steps.
  495. """
  496. raise NotImplementedError("Your %s class has not defined a done() "
  497. "method, which is required." % self.__class__.__name__)
  498. class SessionWizardView(WizardView):
  499. """
  500. A WizardView with pre-configured SessionStorage backend.
  501. """
  502. storage_name = 'django.contrib.formtools.wizard.storage.session.SessionStorage'
  503. class CookieWizardView(WizardView):
  504. """
  505. A WizardView with pre-configured CookieStorage backend.
  506. """
  507. storage_name = 'django.contrib.formtools.wizard.storage.cookie.CookieStorage'
  508. class NamedUrlWizardView(WizardView):
  509. """
  510. A WizardView with URL named steps support.
  511. """
  512. url_name = None
  513. done_step_name = None
  514. @classmethod
  515. def get_initkwargs(cls, *args, **kwargs):
  516. """
  517. We require a url_name to reverse URLs later. Additionally users can
  518. pass a done_step_name to change the URL name of the "done" view.
  519. """
  520. assert 'url_name' in kwargs, 'URL name is needed to resolve correct wizard URLs'
  521. extra_kwargs = {
  522. 'done_step_name': kwargs.pop('done_step_name', 'done'),
  523. 'url_name': kwargs.pop('url_name'),
  524. }
  525. initkwargs = super(NamedUrlWizardView, cls).get_initkwargs(*args, **kwargs)
  526. initkwargs.update(extra_kwargs)
  527. assert initkwargs['done_step_name'] not in initkwargs['form_list'], \
  528. 'step name "%s" is reserved for "done" view' % initkwargs['done_step_name']
  529. return initkwargs
  530. def get_step_url(self, step):
  531. return reverse(self.url_name, kwargs={'step': step})
  532. def get(self, *args, **kwargs):
  533. """
  534. This renders the form or, if needed, does the http redirects.
  535. """
  536. step_url = kwargs.get('step', None)
  537. if step_url is None:
  538. if 'reset' in self.request.GET:
  539. self.storage.reset()
  540. self.storage.current_step = self.steps.first
  541. if self.request.GET:
  542. query_string = "?%s" % self.request.GET.urlencode()
  543. else:
  544. query_string = ""
  545. return redirect(self.get_step_url(self.steps.current)
  546. + query_string)
  547. # is the current step the "done" name/view?
  548. elif step_url == self.done_step_name:
  549. last_step = self.steps.last
  550. return self.render_done(self.get_form(step=last_step,
  551. data=self.storage.get_step_data(last_step),
  552. files=self.storage.get_step_files(last_step)
  553. ), **kwargs)
  554. # is the url step name not equal to the step in the storage?
  555. # if yes, change the step in the storage (if name exists)
  556. elif step_url == self.steps.current:
  557. # URL step name and storage step name are equal, render!
  558. return self.render(self.get_form(
  559. data=self.storage.current_step_data,
  560. files=self.storage.current_step_files,
  561. ), **kwargs)
  562. elif step_url in self.get_form_list():
  563. self.storage.current_step = step_url
  564. return self.render(self.get_form(
  565. data=self.storage.current_step_data,
  566. files=self.storage.current_step_files,
  567. ), **kwargs)
  568. # invalid step name, reset to first and redirect.
  569. else:
  570. self.storage.current_step = self.steps.first
  571. return redirect(self.get_step_url(self.steps.first))
  572. def post(self, *args, **kwargs):
  573. """
  574. Do a redirect if user presses the prev. step button. The rest of this
  575. is super'd from WizardView.
  576. """
  577. wizard_goto_step = self.request.POST.get('wizard_goto_step', None)
  578. if wizard_goto_step and wizard_goto_step in self.get_form_list():
  579. return self.render_goto_step(wizard_goto_step)
  580. return super(NamedUrlWizardView, self).post(*args, **kwargs)
  581. def get_context_data(self, form, **kwargs):
  582. """
  583. NamedUrlWizardView provides the url_name of this wizard in the context
  584. dict `wizard`.
  585. """
  586. context = super(NamedUrlWizardView, self).get_context_data(form=form, **kwargs)
  587. context['wizard']['url_name'] = self.url_name
  588. return context
  589. def render_next_step(self, form, **kwargs):
  590. """
  591. When using the NamedUrlWizardView, we have to redirect to update the
  592. browser's URL to match the shown step.
  593. """
  594. next_step = self.get_next_step()
  595. self.storage.current_step = next_step
  596. return redirect(self.get_step_url(next_step))
  597. def render_goto_step(self, goto_step, **kwargs):
  598. """
  599. This method gets called when the current step has to be changed.
  600. `goto_step` contains the requested step to go to.
  601. """
  602. self.storage.current_step = goto_step
  603. return redirect(self.get_step_url(goto_step))
  604. def render_revalidation_failure(self, failed_step, form, **kwargs):
  605. """
  606. When a step fails, we have to redirect the user to the first failing
  607. step.
  608. """
  609. self.storage.current_step = failed_step
  610. return redirect(self.get_step_url(failed_step))
  611. def render_done(self, form, **kwargs):
  612. """
  613. When rendering the done view, we have to redirect first (if the URL
  614. name doesn't fit).
  615. """
  616. if kwargs.get('step', None) != self.done_step_name:
  617. return redirect(self.get_step_url(self.done_step_name))
  618. return super(NamedUrlWizardView, self).render_done(form, **kwargs)
  619. class NamedUrlSessionWizardView(NamedUrlWizardView):
  620. """
  621. A NamedUrlWizardView with pre-configured SessionStorage backend.
  622. """
  623. storage_name = 'django.contrib.formtools.wizard.storage.session.SessionStorage'
  624. class NamedUrlCookieWizardView(NamedUrlWizardView):
  625. """
  626. A NamedUrlFormWizard with pre-configured CookieStorageBackend.
  627. """
  628. storage_name = 'django.contrib.formtools.wizard.storage.cookie.CookieStorage'