3 from django import forms
4 from django.conf import settings
6 class Form(forms.Form):
9 class ModelForm(forms.ModelForm):
11 Subclass of `forms.ModelForm` which makes sure
12 that the initial values are present in the form
13 data, so you don't have to send all old values
14 for the form to actually validate. Django does not
15 do this on its own, which is really annoying.
17 def merge_from_initial(self):
18 self.data._mutable = True
19 filt = lambda v: v not in self.data.keys()
20 for field in filter(filt, getattr(self.Meta, 'fields', ())):
21 self.data[field] = self.initial.get(field, None)
24 class OAuthAuthenticationForm(forms.Form):
25 oauth_token = forms.CharField(widget=forms.HiddenInput)
26 oauth_callback = forms.CharField(widget=forms.HiddenInput, required=False)
27 authorize_access = forms.BooleanField(required=True)
28 csrf_signature = forms.CharField(widget=forms.HiddenInput)
30 def __init__(self, *args, **kwargs):
31 forms.Form.__init__(self, *args, **kwargs)
33 self.fields['csrf_signature'].initial = self.initial_csrf_signature
35 def clean_csrf_signature(self):
36 sig = self.cleaned_data['csrf_signature']
37 token = self.cleaned_data['oauth_token']
39 sig1 = OAuthAuthenticationForm.get_csrf_signature(settings.SECRET_KEY, token)
42 raise forms.ValidationError("CSRF signature is not valid")
46 def initial_csrf_signature(self):
47 token = self.initial['oauth_token']
48 return OAuthAuthenticationForm.get_csrf_signature(settings.SECRET_KEY, token)
51 def get_csrf_signature(key, token):
55 hashed = hmac.new(key, token, hashlib.sha1)
57 import sha # deprecated
58 hashed = hmac.new(key, token, sha)
60 # calculate the digest base 64
61 return base64.b64encode(hashed.digest())