class ImportContactsForm(Form): ACCOUNT_TYPES = ( ('Gmail', '@gmail.com'), ('Hotmail', '@hotmail.com'), ('Yahoo', '@yahoo.com'), ('Facebook', '@facebook.com'), ) email = forms.CharField(label=_('Email'), required=True) password = forms.CharField(label=_('Password'), widget=forms.PasswordInput(), required=True) account_type = forms.CharField(label=_('Account type'), required=True) manual_contacts = forms.CharField(widget=forms.HiddenInput(), required=False) def clean_password(self): return self.cleaned_data['password'].replace('"', r'\"') def clean_account_type(self): try: return dict(self.ACCOUNT_TYPES)[self.cleaned_data['account_type']] except ValueError: raise forms.ValidationError('Wrong email address supplied.') def clean_email(self): print 1 if set(self.cleaned_data['email']).intersection(' @'): raise forms.ValidationError("Your email login can't contain special chars.") return self.cleaned_data['email'] def clean_manual_contacts(self): try: self.manual = simplejson.loads(self.cleaned_data['manual_contacts']) except ValueError: # Beware, we are not raising error when can't understand incoming format here self.manual = {} def get_contacts_web(self): email = ''.join([self.cleaned_data['email'], self.cleaned_data['account_type']]) # for dev testing # making password to login to dev site password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() password_mgr.add_password(None, settings.CONTACT_IMPORTER_URL, settings.CONTACT_IMPORTER_WEB['login'], settings.CONTACT_IMPORTER_WEB['password'],) # building request for it handler = urllib2.HTTPBasicAuthHandler(password_mgr) opener = urllib2.build_opener(handler) urllib2.install_opener(opener) # set values for importer email_values = {'email': email, 'pass': self.cleaned_data['password']} data = urllib.urlencode(email_values) # building and making request req = urllib2.Request(settings.CONTACT_IMPORTER_URL, data) try: response = urllib2.urlopen(req) except urllib2.HTTPError, e: raise forms.ValidationError('HTTP Error! Code: %s' % e.code) else: return response.read() def get_contacts_local(self): email = ''.join([self.cleaned_data['email'], self.cleaned_data['account_type']]) w, data, err = os.popen3('php %s/php/cimporter.php "%s" "%s"' % (os.path.join(os.path.dirname(__file__)), email, self.cleaned_data['password'],)) errors = err.read().strip() if errors: raise forms.ValidationError(errors) return data.read() def clean(self): print 2 super(ImportContactsForm, self).clean() print 3 if settings.CONTACT_IMPORTER_USE_WEB: self.json_contacts = self.get_contacts_web() else: self.json_contacts = self.get_contacts_local() try: self.contacts = simplejson.loads(self.json_contacts) except ValueError, e: raise forms.ValidationError(e.message) def save(self): return (self.json_contacts, self.contacts, self.manual) OUTPUT: Development server is running at http://127.0.0.1:8000/ Quit the server with CONTROL-C. 2 3 [14/Feb/2008 15:13:32] "POST /invite/friends/ HTTP/1.1" 500 139235