Created
November 9, 2012 10:47
-
-
Save beniwohli/4045110 to your computer and use it in GitHub Desktop.
A form that validates that the user doesn't change (some) hidden inputs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django import forms | |
from django.core import signing | |
from django.utils.translation import ugettext_lazy as _ | |
class SignedForm(forms.Form): | |
bad_signature_error = _("You've been a naughty boy!") | |
signed_fields = None | |
signature = forms.CharField(widget=forms.HiddenInput, required=True) | |
def __init__(self, *args, **kwargs): | |
super(SignedForm, self).__init__(*args, **kwargs) | |
if self.signed_fields: | |
data = {field: unicode(self.initial.get(field)) if self.initial.get(field) is not None else '' for field in self.signed_fields} | |
self.fields['signature'].initial = signing.dumps(data) | |
else: | |
self.fields['signature'].required = False | |
def clean_signature(self): | |
try: | |
return signing.loads(self.cleaned_data['signature']) | |
except signing.BadSignature: | |
raise forms.ValidationError(self.bad_signature_error) | |
def clean(self): | |
if self.signed_fields: | |
data = {field: self.data.get(field) for field in self.signed_fields} | |
signed_data = self.cleaned_data['signature'] | |
for key, value in data.items(): | |
if signed_data[key] != value: | |
raise forms.ValidationError(self.bad_signature_error) | |
return self.cleaned_data |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment