def test_registration_social(self): """Verify the registration process works with the social flow. When a user logs in for the first time using an unknown social account, she has to fill out the registration form before she is let in. """ response = self.social_testing_login() # A registration form is displayed to the user. self.assertRedirects(response, '/account/register/') # The registration form is supposed to be filled in with values # retrieved from the auth provider. self.assertContains( response, b'<input id="id_username" maxlength="30" name="username" type="text" value="koniiiik" />', html=True, ) self.assertContains( response, b'<input id="id_first_name" maxlength="30" name="first_name" type="text" value="Colleague" />', html=True, ) self.assertContains( response, b'<input id="id_last_name" maxlength="30" name="last_name" type="text" value="Knuk" />', html=True, ) # The type of an EmailInput has changed in 1.6, which means we # need to render it manually here. Also, EmailField.max_length # changed in 1.8. expected = EmailField().widget.render('email', '*****@*****.**', { 'maxlength': models.EmailField().max_length, 'id': 'id_email' }) self.assertContains( response, expected.encode('utf-8'), html=True, ) # Submit the registration form... data = { 'username': '******', 'email': '*****@*****.**', 'first_name': 'Colleague', 'last_name': 'Knuk', } response = self.client.post('/account/register/', data, follow=True) # The redirect chain continues through the social:complete view # and lands at the LOGIN_URL destination. self.assertIn(tuple(response.redirect_chain), [(('http://testserver/account/complete/test1/', 302), ('http://testserver/account/', 302)), (('/account/complete/test1/', 302), ('/account/', 302))]) # The resulting page shows the user logged in and with a social # association. self.assertIn(b'Logged in as', response.content) self.assertIn(b'<a href="/account/" class="navbar-link">koniiiik</a>', response.content) self.assertIn(b'Testing UID #1', response.content)
def is_valid(self, email): """ Renvoyer si une adresse email a un format valide """ field = EmailField() try: field.clean(email) return True except ValidationError: return False
def test_registration_social(self): """Verify the registration process works with the social flow. When a user logs in for the first time using an unknown social account, she has to fill out the registration form before she is let in. """ response = self.social_testing_login() # A registration form is displayed to the user. self.assertRedirects(response, '/account/register/') # The registration form is supposed to be filled in with values # retrieved from the auth provider. self.assertContains( response, b'<input id="id_username" maxlength="30" name="username" type="text" value="koniiiik" />', html=True, ) self.assertContains( response, b'<input id="id_first_name" maxlength="30" name="first_name" type="text" value="Colleague" />', html=True, ) self.assertContains( response, b'<input id="id_last_name" maxlength="30" name="last_name" type="text" value="Knuk" />', html=True, ) # The type of an EmailInput has changed in 1.6, which means we # need to render it manually here. expected = EmailField().widget.render('email', '*****@*****.**', { 'maxlength': 75, 'id': 'id_email' }) self.assertContains( response, expected.encode('utf-8'), html=True, ) # Submit the registration form... data = { 'username': '******', 'email': '*****@*****.**', 'first_name': 'Colleague', 'last_name': 'Knuk', } response = self.client.post('/account/register/', data, follow=True) # The redirect chain continues through the social:complete view # and lands at the LOGIN_URL destination. self.assertEqual(response.redirect_chain, [('http://testserver/account/complete/test1/', 302), ('http://testserver/account/', 302)]) # The resulting page shows the user logged in and with a social # association. self.assertIn(b'Logged in as', response.content) self.assertIn(b'<a href="/account/" class="navbar-link">koniiiik</a>', response.content) self.assertIn(b'Testing UID #1', response.content)
class RegForm(forms.Form): name = CharField(max_length=30, required=False) username = CharField( min_length=2, max_length=30, help_text= "30 characters or fewer. Alphanumeric characters only (letters, digits and underscores)", widget=TextInput( attrs={ "onfocus": "showRegHelp('username');", "onblur": "hideRegHelp('username');return checkUsername();" })) email = EmailField() password = CharField(widget=PasswordInput) confirm_password = CharField(widget=PasswordInput) next = CharField(widget=HiddenInput(), required=False) imghash = CharField(widget=HiddenInput(), required=True) imgtext = CharField( required=True, help_text="Please be case sensitive. 'A' is not the same as 'a'.", widget=TextInput( attrs={ "onfocus": "showRegHelp('captcha');", "onblur": "hideRegHelp('captcha')" })) agree_to_terms = BooleanField(required=True)
class CreateUserForm(UserCreationForm): error_messages = { 'password_mismatch': _('您輸入的兩個密碼並不相符,請再試一次。'), } username = EmailField( label='', widget=EmailInput(attrs={ 'placeholder': 'Email', 'input_prepend_icon': 'cil-user' }), ) password1 = CharField( label='', widget=PasswordInput(attrs={ 'placeholder': 'Password', 'input_prepend_icon': 'cil-lock-locked' }), ) password2 = CharField( label='', widget=PasswordInput( attrs={ 'placeholder': 'Repeat password', 'input_prepend_icon': 'cil-lock-locked' }), )
class ClientFilterForm(forms.Form): model = Clients q = forms.CharField(required=False, widget=forms.TextInput(attrs={'class': 'TinputText'}), label='Search') id = forms.IntegerField(required=False, label='Id') email = EmailField(required=False, label='Email') first_name = forms.IntegerField(required=False, label='First Name') status = forms.MultipleChoiceField(required=False, widget=forms.CheckboxSelectMultiple(), label='Status') phone_number = forms.IntegerField(required=False, label='Phone Number') groups = FilterChoiceField( required=False, queryset=Group.objects.annotate(filter_count=Count('clients')), widget=forms.CheckboxSelectMultiple(), label='Groups', ) class Meta: model = Clients fields = []
class AppScaffoldingForm(Form): name = CharField(max_length=80, label=_('App name'), validators=[validate_id], help_text=_('The app name must be camel case e.g. MyApp')) platform = ChoiceField(choices=lazy(get_versions, list), required=True, label=_('Nextcloud version')) author_name = CharField(max_length=80, label=_('Author\'s full name')) author_email = EmailField(label=_('Author\'s e-mail')) author_homepage = URLField(label=_('Author\'s homepage'), required=False) issue_tracker = URLField(label=_('Issue tracker URL'), required=True, help_text=_('Bug reports and feature requests')) categories = MultipleChoiceField(required=True, label=_('Categories'), choices=lazy(get_categories, list), help_text=_('Hold down CTRL and click to ' 'select multiple entries')) summary = CharField( max_length=256, label=_('Summary'), help_text= _('Short description of your app that will be rendered as short teaser' )) description = CharField(widget=Textarea, label=_('Description'), help_text=_('Full description of what your app ' 'does. Can contain Markdown.'))
class Address(SoColissimoSchema): """ Address schema, shared by sender and recipient """ soap_type_name = "AddressVO" COUNTRIES = [('FR', 'France'), ('MC', 'Monaco')] CIVILITIES = ['M', 'Mlle', 'Mme'] Name = CharField(required=False, help_text='Nom') Surname = CharField(required=False, help_text='Prénom') email = EmailField(required=False) line2 = CharField(required=True, help_text='Numéro et libellé de voie') countryCode = ChoiceField(required=True, choices=COUNTRIES) city = CharField(required=True) postalCode = CharField(required=True) companyName = CharField(required=False) Civility = ChoiceField(required=False, choices=[(c, c) for c in CIVILITIES]) line0 = CharField(required=False, help_text='Etage, couloir, escalier, n° d’appartement') line1 = CharField(required=False, help_text='Entrée, bâtiment, immeuble, résidence') line3 = CharField(required=False, help_text='Lieu dit ou autre mention spéciale') phone = CharField(required=False) MobileNumber = CharField(required=False) DoorCode1 = CharField(required=False) DoorCode2 = CharField(required=False) Interphone = CharField(required=False)
class UserForm(forms.Form): """ A form to validate User resources """ username = CharField(min_length=3, required=True) email = EmailField(min_length=3, required=True) password = CharField(widget=forms.PasswordInput()) def __init__(self, user_object=None, **kwargs): super(UserForm, self).__init__(**kwargs)
class MainForm(Form): """A form for the email and location, with the locations sorted alphabetically""" email = EmailField(widget=EmailInput()) location = ChoiceField() def __init__(self, *args, **kwargs): super(MainForm, self).__init__(*args, **kwargs) locations = sorted( '{}, {}'.format(model.city, model.state) for index, model in enumerate(WeatherModel.objects.all())) self.fields['location'].choices = ( (index, location) for index, location in enumerate(locations))
class SignupForm(Form): first_name = CharField(max_length=255, required=True, widget=TextInput, label=_('First Name')) last_name = CharField(max_length=255, required=True, widget=TextInput, label=_('Last Name')) user_name = CharField(max_length=255, required=False, widget=TextInput, label=_('User Name')) email = EmailField(max_length=255, required=True, widget=EmailInput, label=_('E-mail Address')) password = CharField(min_length=8, max_length=255, required=True, widget=PasswordInput, label=_('Password')) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field in self.fields.values(): field.widget.attrs["class"] = "form-control" def create_user(self): first_name = self.cleaned_data.get('first_name') last_name = self.cleaned_data.get('last_name') user_name = self.cleaned_data.get('user_name') email = self.cleaned_data['email'] password = self.cleaned_data['password'] user = None try: user = User.objects.create_user( email, password, first_name=first_name, last_name=last_name, user_name=user_name, ) except: self.add_error(None, 'Error') return user def clean_email(self): email = self.cleaned_data['email'] if User.objects.filter(email=email).count() > 0: self.add_error('email', _('E-mail Address is already being used.')) return email
class FacebookConnectForm(forms.Form): username = CharField( min_length=2, max_length=30, help_text= "30 characters or fewer. Alphanumeric characters only (letters, digits and underscores)", widget=TextInput( attrs={ "onfocus": "showRegHelp('username');", "onblur": "hideRegHelp('username');return checkUsername();", "onkeyup": "return checkUsername();" })) email = EmailField()
class ContactsForm(Form): name = CharField( label="Nimesi", required=False ) email = EmailField( label="Sähköpostiosoitteesi", required=False ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) fields = list(self.fields.keys())[2:] + ['name', 'email'] self.fields = OrderedDict((k, self.fields[k]) for k in fields)
class RegisterForm(Form): """ username/password/confirm login form. """ username = UsernameField() email = EmailField() password = CharField(widget=PasswordInput) password_confirm = CharField(widget=PasswordInput) def clean(self): cleaned_data = super().clean() if cleaned_data['password'] != cleaned_data['password_confirm']: raise ValidationError("Passwords do not match") return cleaned_data
def __init__(self, request=None, *args, **kwargs): self.request = request self.user_cache = None super(OrigAuthenticationForm, self).__init__(*args, **kwargs) # Set the max length and label for the "username" field. self.username_field = EmailField(label="email", help_text="Email address") self.username_field.verbose_name = 'Email' username_max_length = 255 self.fields['username'].max_length = username_max_length self.fields['username'].widget.attrs['maxlength'] = username_max_length self.fields['username'].widget.attrs['class'] = 'form-control' self.fields['username'].widget.attrs['placeholder'] = 'Email or username' self.fields['username'].label = 'Email' self.fields['password'].widget.attrs['class'] = 'form-control' self.fields['password'].widget.attrs['placeholder'] = 'Password'
class CustomPasswordResetForm(PasswordResetForm): email = EmailField(label=_('Email'), max_length=254, widget=EmailInput( attrs={ 'class': 'form-control', 'autocomplete': 'email', 'placeholder': 'Email' })) def save(self, request, from_email, **kwargs): super().save( from_email=from_email, subject_template_name='includes/emails/password_reset_subject.txt', email_template_name='includes/emails/password_reset_email.html', request=request, **kwargs)
def __init__(self, request=None, *args, **kwargs): super().__init__(request, *args, **kwargs) self.fields['username'] = EmailField( label='', widget=EmailInput(attrs={ 'placeholder': 'Email', 'input_prepend_icon': 'cil-user' }), ) self.fields['password'] = CharField( label='', widget=PasswordInput(attrs={ 'placeholder': 'Password', 'input_prepend_icon': 'cil-lock-locked' }), )
class BeginPasswordResetForm(PasswordResetForm): email = EmailField( label='Email', max_length=254, widget=EmailInput( attrs={ 'autocomplete': 'email', 'class': 'border border-gray-400 rounded-full focus:border-blue-500 focus:outline-none w-88 h-10 pl-3' })) def clean_email(self): data = self.cleaned_data['email'] if not User.objects.filter(email=data).all(): raise ValidationError( "We couldn't find your account with that information.") return data def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs)
class SignupForm(BootstrapFormMixin, Form): # icon = models.ImageField(upload_to=icon_file_path, null=True, blank=True) name = CharField(max_length=256, required=True, widget=TextInput(attrs={'placeholder': 'ユーザーネーム'})) email = EmailField(max_length=256, required=True, widget=TextInput(attrs={'placeholder': 'メールアドレス'})) password = CharField( min_length=8, max_length=256, required=True, widget=PasswordInput(attrs={'placeholder': 'パスワード(8文字以上)'})) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def create_user(self): if 'name' in self.cleaned_data: name = self.cleaned_data['name'] else: name = None email = self.cleaned_data['email'] password = self.cleaned_data['password'] user = None try: if name: user = User.objects.create_user(email, password, name=name) else: user = User.objects.create_user(email, password) except: self.add_error('password', 'ユーザーの作成に失敗しました.') return user def clean_email(self): email = self.cleaned_data['email'] if User.objects.filter(email=email).count() > 0: self.add_error('email', 'そのメールアドレスは既に使われています.') return email
class UnsubscribeForm(Form): email = EmailField(label=_('email address')) def clean(self): email = self.cleaned_data.get('email') try: subscription = Subscription.objects.get(email=email) except Subscription.DoesNotExist: raise ValidationError(ugettext(u'Email address not found.')) self.cleaned_data['subscription'] = subscription def save(self): subscription = self.cleaned_data['subscription'] subscription.active = False subscription.save() context = {'subscription': subscription} # refactor to send_noreply_mail send_noreply_mail( ugettext(u'Unsubscribe from Wolne Lektury\'s newsletter.'), render_to_string('newsletter/unsubscribe_email.html', context), [subscription.email], fail_silently=True)
def __init__( self, required=True, widget=None, max_length=None, fieldsetup_id=None, email_attrs=None, code_attrs=None, email_label=_('e-mail'), send_label=_('send verification code to given e-mail address'), sent_message=_( 'The verification code has been sent to you e-mail address. ' 'You wil receive it within several minutes. Please, also check your SPAM folder.' ), code_label=_('verification code'), **kwargs): self.fieldsetup_id = fieldsetup_id or str(abs(hash(self))) self.fieldsetup = fieldsetups.setdefault( self.fieldsetup_id, VerifiedEmailFieldSetup(**kwargs)) self.widget = widget or VerifiedEmailWidget( email_attrs=email_attrs, code_attrs=code_attrs, email_label=email_label, send_label=send_label, send_url=reverse_lazy('verified-email-field:send', args=(self.fieldsetup_id, )), sent_message=sent_message, code_label=code_label, fieldsetup_id=self.fieldsetup_id, ) super(VerifiedEmailField, self).__init__(( EmailField(label=email_label, required=required), VerificationCodeField(label=code_label, required=False, length=self.fieldsetup.code_length), ), require_all_fields=False, **kwargs)
class SigninForm(BootstrapFormMixin, Form): email = EmailField( max_length=256, required=True, widget=TextInput(attrs={'placeholder': 'メールアドレス'})) password = CharField( max_length=256, required=True, widget=PasswordInput(attrs={'placeholder': 'パスワード'})) def clean_email(self): email = self.cleaned_data['email'] if User.objects.filter(email=email).count() == 0: self.add_error('password', 'メールアドレスかパスワードが正しくありません。') return email def get_authenticated_user(self): user = authenticate( username=self.cleaned_data['email'], password=self.cleaned_data['password']) if user is None: self.add_error('password', 'メールアドレスかパスワードが正しくありません。') return user
class LoginForm(forms.Form): email = EmailField( widget=forms.TextInput(attrs={'autofocus': True}), ) password = forms.CharField( strip=False, widget=forms.PasswordInput, ) def __init__(self, request=None, *args, **kwargs): # Basically a copy of from django.contrib.auth.forms.AuthenticationForm self.request = request self.user_cache = None super(LoginForm, self).__init__(*args, **kwargs) def clean(self): username = self.cleaned_data.get('email') if username: username = username.lower() password = self.cleaned_data.get('password') if username is not None and password: self.user_cache = authenticate(self.request, username=username, password=password) if self.user_cache is None: raise ValidationError("Please enter a correct email and password.", code='invalid_login') elif not self.user_cache.is_active: raise ValidationError("This account is inactive.", code='inactive') return self.cleaned_data def get_user_id(self): if self.user_cache: return self.user_cache.id return None def get_user(self): return self.user_cache
def __init__(self, required=True, fieldsetup_id=None, max_length=None, email_label=_('e-mail'), send_label=_('send verification code'), code_label=_('verification code'), **kwargs): self.fieldsetup_id = fieldsetup_id or str(hash(self)) self.fieldsetup = fieldsetups.setdefault( self.fieldsetup_id, VerifiedEmailFieldSetup(**kwargs)) self.widget = VerifiedEmailWidget( send_label=send_label, fieldsetup_id=self.fieldsetup_id, email_attrs={'placeholder': email_label}, code_attrs={'placeholder': code_label}, ) super(VerifiedEmailField, self).__init__(( EmailField(label=email_label, required=required), VerificationCodeField(label=code_label, length=self.fieldsetup.code_length), ), require_all_fields=False, **kwargs)
def before_import_row(self, row, **kwargs): EmailField().run_validators(row.get('email')) PhoneNumberField().run_validators(row.get('phone'))
class EntityEmailForm(base_forms.CremeModelForm): """Mails are related to the selected contacts/organisations & the 'current' entity. Mails are send to selected contacts/organisations. """ sender = EmailField(label=_('Sender')) c_recipients = MultiCreatorEntityField(label=_('Contacts'), required=False, model=Contact, q_filter={'email__gt': ''}) o_recipients = MultiCreatorEntityField(label=_('Organisations'), required=False, model=Organisation, q_filter={'email__gt': ''}) send_me = BooleanField(label=_('Send me a copy of this mail'), required=False) error_messages = { 'no_person': _('Select at least a Contact or an Organisation'), } blocks = base_forms.FieldBlockManager( ('recipients', _('Who'), ['user', 'sender', 'send_me', 'c_recipients', 'o_recipients']), ('content', _('What'), ['subject', 'body', 'body_html']), ('extra', _('With'), ['signature', 'attachments']), ) class Meta: model = EntityEmail fields = ('user', 'sender', 'subject', 'body', 'body_html', 'signature', 'attachments') def __init__(self, entity, *args, **kwargs): super().__init__(*args, **kwargs) self.entity = entity if isinstance(entity, (Contact, Organisation)): fn, msg = ('c_recipients', _('Beware: the contact «{}» has no email address!')) \ if isinstance(entity, Contact) else \ ('o_recipients', _('Beware: the organisation «{}» has no email address!')) field = self.fields[fn] if entity.email: field.initial = [entity.pk] else: field.help_text = msg.format(entity) self.user_contact = contact = self.user.linked_contact if contact.email: self.fields['sender'].initial = contact.email def finalize_recipient_field(name, model): if FieldsConfig.get_4_model(model).is_fieldname_hidden('email'): self.fields[name] = CharField( label=self.fields[name].label, required=False, widget=Label, initial=gettext( 'Beware: the field «Email address» is hidden ;' ' please contact your administrator.'), ) finalize_recipient_field('c_recipients', Contact) finalize_recipient_field('o_recipients', Organisation) def _clean_recipients(self, field_name): if isinstance(self.fields[field_name].widget, Label): return [] recipients = self.cleaned_data.get(field_name) or [] bad_entities = [] for entity in recipients: try: validate_email(entity.email) except ValidationError: bad_entities.append(entity) if bad_entities: msg_format = gettext('The email address for {} is invalid') user = self.user for entity in bad_entities: self.add_error(field_name, msg_format.format(entity.allowed_str(user))) return recipients def clean_c_recipients(self): return self._clean_recipients('c_recipients') def clean_o_recipients(self): return self._clean_recipients('o_recipients') def clean(self): cdata = super().clean() if not self._errors and not cdata['c_recipients'] and not cdata[ 'o_recipients']: raise ValidationError(self.error_messages['no_person'], code='no_person') return cdata def save(self): cdata = self.cleaned_data get_data = cdata.get sender = get_data('sender') subject = get_data('subject') body = get_data('body') body_html = get_data('body_html') signature = get_data('signature') attachments = get_data('attachments') user = get_data('user') sending_error = False def create_n_send_mail(recipient_address): nonlocal sending_error email = EntityEmail.create_n_send_mail( sender=sender, recipient=recipient_address, subject=subject, user=user, body=body, body_html=body_html, signature=signature, attachments=attachments, ) if email.status == MAIL_STATUS_SENDINGERROR: sending_error = True return email with atomic(): if get_data('send_me'): create_n_send_mail(sender) user_contact = self.user_contact create_relation = partial(Relation.objects.create, user=user) for recipient in chain(cdata['c_recipients'], cdata['o_recipients']): email = create_n_send_mail(recipient.email) create_relation(subject_entity=email, type_id=REL_SUB_MAIL_SENDED, object_entity=user_contact) create_relation(subject_entity=email, type_id=REL_SUB_MAIL_RECEIVED, object_entity=recipient) if sending_error: entity_emails_send_type.refresh_job()
class EnrollForm(Form): email = EmailField(required=True, label='邮箱') course_id = IntegerField(required=True, validators=[validate_enroll], label='课程')
class LogInForm(AuthenticationForm): username = EmailField()
class SignInForm(UserCreationForm): email = EmailField(label=_('Email address')) class Meta(UserCreationForm.Meta): model = User fields = ['username', 'email', 'password1', 'password2']
def check(email): field = EmailField() return field.clean(email.strip())
class _MockRegistrationForm(Form): full_name = CharField(max_length=255) email_address = EmailField(max_length=255)
class ReporterRegistrationForm(Form): required_css_class = 'required' name = RegexField(regex="[^0-9.,\s@#$%&*~]*", max_length=80, error_message=_("Please enter a valid value containing only letters a-z or A-Z or symbols '`- "), label=_("Name"), required=False) telephone_number = PhoneNumberField(required=True, label=_("Mobile Number"), error_message=_("Please enter a valid phone number.")) geo_code = CharField(max_length=30, required=False, label=_("GPS Coordinates")) location = CharField(max_length=500, required=False, label=_("Name")) project_id = CharField(required=False, widget=HiddenInput()) DEVICE_CHOICES = (('sms', mark_safe('<img src="/media/images/mini_mobile.png" /> <span>SMS</span>')), ( 'web', mark_safe('<img src="/media/images/mini_computer.png" /> <span>Web</span>' + smartphone_icon()))) devices = MultipleChoiceField(label=_('Device'), widget=CheckboxSelectMultiple(), choices=DEVICE_CHOICES, initial=['sms'], required=False, ) email = EmailField(required=False, widget=TextInput(attrs=dict({'class': 'required'}, maxlength=75)), label=_("E-Mail"), error_messages={ 'invalid': _('Enter a valid email address. Example:[email protected]')}) short_code = CharField(required=False, max_length=12, label=_("ID"), widget=TextInput(attrs=dict({'class': 'subject_field'}))) generated_id = BooleanField(required=False, initial=True) # Needed for telephone number validation org_id = None def __init__(self, org_id=None, *args, **kwargs): self.org_id = org_id super(ReporterRegistrationForm, self).__init__(*args, **kwargs) def _is_int(self, s): try: int(s) return True except ValueError: return False def _geo_code_format_validations(self, lat_long, msg): if len(lat_long) != 2: self._errors['geo_code'] = self.error_class([msg]) else: try: if not (-90 < float(lat_long[0]) < 90 and -180 < float(lat_long[1]) < 180): self._errors['geo_code'] = self.error_class([msg]) except Exception: self._errors['geo_code'] = self.error_class([msg]) def _geo_code_validations(self): geo_code = self.cleaned_data.get("geo_code").strip() if not bool(geo_code): return msg = _( "Incorrect GPS format. The GPS coordinates must be in the following format: xx.xxxx,yy.yyyy. Example -18.8665,47.5315") geo_code_string = geo_code.strip() geo_code_string = geo_code_string.replace(",", " ") geo_code_string = re.sub(' +', ' ', geo_code_string) if not is_empty(geo_code_string): lat_long = geo_code_string.split(" ") self._geo_code_format_validations(lat_long, msg) self.cleaned_data['geo_code'] = geo_code_string def clean(self): self.convert_email_to_lowercase() if not self.cleaned_data.get('generated_id') and not self.cleaned_data.get('short_code'): msg = _('This field is required.') self.errors['short_code'] = self.error_class([msg]) self._geo_code_validations() if not self.cleaned_data.get('project_id'): self.cleaned_data['is_data_sender'] = False else: self.cleaned_data['is_data_sender'] = 'True' return self.cleaned_data def clean_short_code(self): short_code = self.cleaned_data.get('short_code') if short_code: if len(short_code) > 12: msg = _("Unique ID should be less than 12 characters") self.errors['short_code'] = self.error_class([msg]) if not re.match("^[a-zA-Z0-9]+$", short_code): msg = _("Only letters and numbers are valid") self.errors['short_code'] = self.error_class([msg]) return short_code def clean_telephone_number(self): """ Validate telephone number. This expects the dbm to be set on the form before trying to clean. """ organization = Organization.objects.get(org_id=self.org_id) mobile_number = self.cleaned_data.get('telephone_number') if organization.in_trial_mode: datasender_filter = DataSenderOnTrialAccount.objects.filter(mobile_number=(mobile_number)) if datasender_filter.exclude(organization=organization).exists(): self._errors['telephone_number'] = self.error_class( [_(u"Sorry, this number has already been used for a different DataWinners Basic account.")]) return mobile_number def clean_email(self): """ Validate that the supplied email address is unique for the site. """ email = self.cleaned_data.get('email') if not email: return email if datasender_count_with(email) > 0: raise forms.ValidationError( _("This email address is already in use. Please supply a different email address.")) return self.cleaned_data['email'] def convert_email_to_lowercase(self): email = self.cleaned_data.get('email') if email is not None: self.cleaned_data['email'] = email.lower() def requires_web_access(self): return self.cleaned_data.get('email') def update_errors(self, validation_errors): mapper = {MOBILE_NUMBER_FIELD_CODE: 'telephone_number', GEO_CODE: GEO_CODE_FIELD_NAME} for field_code, error in validation_errors.iteritems(): self._errors[mapper.get(field_code)] = self.error_class([_(error)])