PageRenderTime 28ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/servicios_web/gae/django-guestbook/src/django/contrib/formtools/wizard.py

https://github.com/navarro81/curso_python_dga_11
Python | 283 lines | 263 code | 0 blank | 20 comment | 1 complexity | 297da6248e36f29b6e26d0a51106ea2c MD5 | raw file
  1. """
  2. FormWizard class -- implements a multi-page form, validating between each
  3. step and storing the form's state as HTML hidden fields so that no state is
  4. stored on the server side.
  5. """
  6. import cPickle as pickle
  7. from django import forms
  8. from django.conf import settings
  9. from django.contrib.formtools.utils import security_hash, form_hmac
  10. from django.http import Http404
  11. from django.shortcuts import render_to_response
  12. from django.template.context import RequestContext
  13. from django.utils.crypto import constant_time_compare
  14. from django.utils.hashcompat import md5_constructor
  15. from django.utils.translation import ugettext_lazy as _
  16. from django.utils.decorators import method_decorator
  17. from django.views.decorators.csrf import csrf_protect
  18. class FormWizard(object):
  19. # The HTML (and POST data) field name for the "step" variable.
  20. step_field_name="wizard_step"
  21. # METHODS SUBCLASSES SHOULDN'T OVERRIDE ###################################
  22. def __init__(self, form_list, initial=None):
  23. """
  24. Start a new wizard with a list of forms.
  25. form_list should be a list of Form classes (not instances).
  26. """
  27. self.form_list = form_list[:]
  28. self.initial = initial or {}
  29. # Dictionary of extra template context variables.
  30. self.extra_context = {}
  31. # A zero-based counter keeping track of which step we're in.
  32. self.step = 0
  33. def __repr__(self):
  34. return "step: %d\nform_list: %s\ninitial_data: %s" % (self.step, self.form_list, self.initial)
  35. def get_form(self, step, data=None):
  36. "Helper method that returns the Form instance for the given step."
  37. return self.form_list[step](data, prefix=self.prefix_for_step(step), initial=self.initial.get(step, None))
  38. def num_steps(self):
  39. "Helper method that returns the number of steps."
  40. # You might think we should just set "self.num_steps = len(form_list)"
  41. # in __init__(), but this calculation needs to be dynamic, because some
  42. # hook methods might alter self.form_list.
  43. return len(self.form_list)
  44. def _check_security_hash(self, token, request, form):
  45. expected = self.security_hash(request, form)
  46. if constant_time_compare(token, expected):
  47. return True
  48. else:
  49. # Fall back to Django 1.2 method, for compatibility with forms that
  50. # are in the middle of being used when the upgrade occurs. However,
  51. # we don't want to do this fallback if a subclass has provided their
  52. # own security_hash method - because they might have implemented a
  53. # more secure method, and this would punch a hole in that.
  54. # PendingDeprecationWarning <- left here to remind us that this
  55. # compatibility fallback should be removed in Django 1.5
  56. FormWizard_expected = FormWizard.security_hash(self, request, form)
  57. if expected == FormWizard_expected:
  58. # They didn't override security_hash, do the fallback:
  59. old_expected = security_hash(request, form)
  60. return constant_time_compare(token, old_expected)
  61. else:
  62. return False
  63. @method_decorator(csrf_protect)
  64. def __call__(self, request, *args, **kwargs):
  65. """
  66. Main method that does all the hard work, conforming to the Django view
  67. interface.
  68. """
  69. if 'extra_context' in kwargs:
  70. self.extra_context.update(kwargs['extra_context'])
  71. current_step = self.determine_step(request, *args, **kwargs)
  72. self.parse_params(request, *args, **kwargs)
  73. # Sanity check.
  74. if current_step >= self.num_steps():
  75. raise Http404('Step %s does not exist' % current_step)
  76. # Process the current step. If it's valid, go to the next step or call
  77. # done(), depending on whether any steps remain.
  78. if request.method == 'POST':
  79. form = self.get_form(current_step, request.POST)
  80. else:
  81. form = self.get_form(current_step)
  82. if form.is_valid():
  83. # Validate all the forms. If any of them fail validation, that
  84. # must mean the validator relied on some other input, such as
  85. # an external Web site.
  86. # It is also possible that validation might fail under certain
  87. # attack situations: an attacker might be able to bypass previous
  88. # stages, and generate correct security hashes for all the
  89. # skipped stages by virtue of:
  90. # 1) having filled out an identical form which doesn't have the
  91. # validation (and does something different at the end),
  92. # 2) or having filled out a previous version of the same form
  93. # which had some validation missing,
  94. # 3) or previously having filled out the form when they had
  95. # more privileges than they do now.
  96. #
  97. # Since the hashes only take into account values, and not other
  98. # other validation the form might do, we must re-do validation
  99. # now for security reasons.
  100. current_form_list = [self.get_form(i, request.POST) for i in range(current_step)]
  101. for i, f in enumerate(current_form_list):
  102. if not self._check_security_hash(request.POST.get("hash_%d" % i, ''), request, f):
  103. return self.render_hash_failure(request, i)
  104. if not f.is_valid():
  105. return self.render_revalidation_failure(request, i, f)
  106. else:
  107. self.process_step(request, f, i)
  108. # Now progress to processing this step:
  109. self.process_step(request, form, current_step)
  110. next_step = current_step + 1
  111. if next_step == self.num_steps():
  112. return self.done(request, current_form_list)
  113. else:
  114. form = self.get_form(next_step)
  115. self.step = current_step = next_step
  116. return self.render(form, request, current_step)
  117. def render(self, form, request, step, context=None):
  118. "Renders the given Form object, returning an HttpResponse."
  119. old_data = request.POST
  120. prev_fields = []
  121. if old_data:
  122. hidden = forms.HiddenInput()
  123. # Collect all data from previous steps and render it as HTML hidden fields.
  124. for i in range(step):
  125. old_form = self.get_form(i, old_data)
  126. hash_name = 'hash_%s' % i
  127. prev_fields.extend([bf.as_hidden() for bf in old_form])
  128. prev_fields.append(hidden.render(hash_name, old_data.get(hash_name, self.security_hash(request, old_form))))
  129. return self.render_template(request, form, ''.join(prev_fields), step, context)
  130. # METHODS SUBCLASSES MIGHT OVERRIDE IF APPROPRIATE ########################
  131. def prefix_for_step(self, step):
  132. "Given the step, returns a Form prefix to use."
  133. return str(step)
  134. def render_hash_failure(self, request, step):
  135. """
  136. Hook for rendering a template if a hash check failed.
  137. step is the step that failed. Any previous step is guaranteed to be
  138. valid.
  139. This default implementation simply renders the form for the given step,
  140. but subclasses may want to display an error message, etc.
  141. """
  142. return self.render(self.get_form(step), request, step, context={'wizard_error': _('We apologize, but your form has expired. Please continue filling out the form from this page.')})
  143. def render_revalidation_failure(self, request, step, form):
  144. """
  145. Hook for rendering a template if final revalidation failed.
  146. It is highly unlikely that this point would ever be reached, but See
  147. the comment in __call__() for an explanation.
  148. """
  149. return self.render(form, request, step)
  150. def security_hash(self, request, form):
  151. """
  152. Calculates the security hash for the given HttpRequest and Form instances.
  153. Subclasses may want to take into account request-specific information,
  154. such as the IP address.
  155. """
  156. return form_hmac(form)
  157. def determine_step(self, request, *args, **kwargs):
  158. """
  159. Given the request object and whatever *args and **kwargs were passed to
  160. __call__(), returns the current step (which is zero-based).
  161. Note that the result should not be trusted. It may even be a completely
  162. invalid number. It's not the job of this method to validate it.
  163. """
  164. if not request.POST:
  165. return 0
  166. try:
  167. step = int(request.POST.get(self.step_field_name, 0))
  168. except ValueError:
  169. return 0
  170. return step
  171. def parse_params(self, request, *args, **kwargs):
  172. """
  173. Hook for setting some state, given the request object and whatever
  174. *args and **kwargs were passed to __call__(), sets some state.
  175. This is called at the beginning of __call__().
  176. """
  177. pass
  178. def get_template(self, step):
  179. """
  180. Hook for specifying the name of the template to use for a given step.
  181. Note that this can return a tuple of template names if you'd like to
  182. use the template system's select_template() hook.
  183. """
  184. return 'forms/wizard.html'
  185. def render_template(self, request, form, previous_fields, step, context=None):
  186. """
  187. Renders the template for the given step, returning an HttpResponse object.
  188. Override this method if you want to add a custom context, return a
  189. different MIME type, etc. If you only need to override the template
  190. name, use get_template() instead.
  191. The template will be rendered with the following context:
  192. step_field -- The name of the hidden field containing the step.
  193. step0 -- The current step (zero-based).
  194. step -- The current step (one-based).
  195. step_count -- The total number of steps.
  196. form -- The Form instance for the current step (either empty
  197. or with errors).
  198. previous_fields -- A string representing every previous data field,
  199. plus hashes for completed forms, all in the form of
  200. hidden fields. Note that you'll need to run this
  201. through the "safe" template filter, to prevent
  202. auto-escaping, because it's raw HTML.
  203. """
  204. context = context or {}
  205. context.update(self.extra_context)
  206. return render_to_response(self.get_template(step), dict(context,
  207. step_field=self.step_field_name,
  208. step0=step,
  209. step=step + 1,
  210. step_count=self.num_steps(),
  211. form=form,
  212. previous_fields=previous_fields
  213. ), context_instance=RequestContext(request))
  214. def process_step(self, request, form, step):
  215. """
  216. Hook for modifying the FormWizard's internal state, given a fully
  217. validated Form object. The Form is guaranteed to have clean, valid
  218. data.
  219. This method should *not* modify any of that data. Rather, it might want
  220. to set self.extra_context or dynamically alter self.form_list, based on
  221. previously submitted forms.
  222. Note that this method is called every time a page is rendered for *all*
  223. submitted steps.
  224. """
  225. pass
  226. # METHODS SUBCLASSES MUST OVERRIDE ########################################
  227. def done(self, request, form_list):
  228. """
  229. Hook for doing something with the validated data. This is responsible
  230. for the final processing.
  231. form_list is a list of Form instances, each containing clean, valid
  232. data.
  233. """
  234. raise NotImplementedError("Your %s class has not defined a done() method, which is required." % self.__class__.__name__)