utils.py 891 B

12345678910111213141516171819202122232425262728
  1. from __future__ import unicode_literals
  2. # Do not try cPickle here (see #18340)
  3. import pickle
  4. from django.utils.crypto import salted_hmac
  5. from django.utils import six
  6. def form_hmac(form):
  7. """
  8. Calculates a security hash for the given Form instance.
  9. """
  10. data = []
  11. for bf in form:
  12. # Get the value from the form data. If the form allows empty or hasn't
  13. # changed then don't call clean() to avoid trigger validation errors.
  14. if form.empty_permitted and not form.has_changed():
  15. value = bf.data or ''
  16. else:
  17. value = bf.field.clean(bf.data) or ''
  18. if isinstance(value, six.string_types):
  19. value = value.strip()
  20. data.append((bf.name, value))
  21. pickled = pickle.dumps(data, pickle.HIGHEST_PROTOCOL)
  22. key_salt = 'django.contrib.formtools'
  23. return salted_hmac(key_salt, pickled).hexdigest()