2008-08-27 04:19:12 +08:00
|
|
|
try:
|
|
|
|
import cPickle as pickle
|
|
|
|
except ImportError:
|
|
|
|
import pickle
|
2008-09-14 15:04:40 +08:00
|
|
|
|
2008-08-27 04:19:12 +08:00
|
|
|
from django.conf import settings
|
|
|
|
from django.utils.hashcompat import md5_constructor
|
|
|
|
from django.forms import BooleanField
|
|
|
|
|
|
|
|
def security_hash(request, form, *args):
|
2008-09-14 15:04:40 +08:00
|
|
|
"""
|
|
|
|
Calculates a security hash for the given Form instance.
|
|
|
|
|
|
|
|
This creates a list of the form field names/values in a deterministic
|
|
|
|
order, pickles the result with the SECRET_KEY setting, then takes an md5
|
|
|
|
hash of that.
|
|
|
|
"""
|
|
|
|
|
2009-05-13 05:54:58 +08:00
|
|
|
data = []
|
|
|
|
for bf in form:
|
2009-05-13 06:02:38 +08:00
|
|
|
# Get the value from the form data. If the form allows empty or hasn't
|
|
|
|
# changed then don't call clean() to avoid trigger validation errors.
|
|
|
|
if form.empty_permitted and not form.has_changed():
|
|
|
|
value = bf.data or ''
|
|
|
|
else:
|
|
|
|
value = bf.field.clean(bf.data) or ''
|
2009-05-13 05:54:58 +08:00
|
|
|
if isinstance(value, basestring):
|
|
|
|
value = value.strip()
|
|
|
|
data.append((bf.name, value))
|
2009-05-13 06:02:38 +08:00
|
|
|
|
2008-09-14 15:04:40 +08:00
|
|
|
data.extend(args)
|
|
|
|
data.append(settings.SECRET_KEY)
|
|
|
|
|
|
|
|
# Use HIGHEST_PROTOCOL because it's the most efficient. It requires
|
2010-05-04 22:00:30 +08:00
|
|
|
# Python 2.3, but Django requires 2.4 anyway, so that's OK.
|
2008-09-14 15:04:40 +08:00
|
|
|
pickled = pickle.dumps(data, pickle.HIGHEST_PROTOCOL)
|
2008-08-27 04:19:12 +08:00
|
|
|
|
2008-09-14 15:04:40 +08:00
|
|
|
return md5_constructor(pickled).hexdigest()
|
2008-08-27 04:19:12 +08:00
|
|
|
|