def to_internal_value(self, data): phone_number = to_python(data) if phone_number and not phonenumbers.is_possible_number(phone_number): # attempting to check if this is a possible Indian number phone_number = to_python(data, region="IN") if phone_number and not phonenumbers.is_possible_number( phone_number): raise ValidationError(self.error_messages["invalid"]) return phone_number
def get_prep_value(self, value): "Returns field's value prepared for saving into a database." if value in (None, ""): return to_python(self.default) or '' value = to_python(value) if isinstance(value, basestring): # it is an invalid phone number return value return value.as_e164
def get_prep_value(self, value): "Returns field's value prepared for saving into a database." if value is None: if not self.blank: return to_python(self.default) elif self.blank: return to_python(self.default) or '' value = to_python(value) if isinstance(value, string_types): # it is an invalid phone number return value return value.as_e164
def get_prep_value(self, value): "Returns field's value prepared for saving into a database." if value is None or value == '': if not self.blank: return to_python(self.default) elif self.blank: return to_python(self.default) or '' value = to_python(value) if isinstance(value, string_types): # it is an invalid phone number return value return value.as_e164
def get_prep_value(self, value): "Returns field's value prepared for saving into a database." if not value: if self.has_default(): return to_python(self.default) if not self.null: return '' return value value = to_python(value) if isinstance(value, string_types): # it is an invalid phone number return value return value.as_e164
def to_internal_value(self, value): phone_number = super().to_internal_value(value) phone_number = to_python(phone_number, region=self.region) if not phone_number: return "" if phone_number.is_valid(): return str(phone_number) if self.region == "FR": for country_code in FRENCH_COUNTRY_CODES: phone_number = to_python(value, country_code) if phone_number.is_valid(): return str(phone_number) self.fail("invalid_format")
def validate_possible_number(phone, country=None): phone_number = to_python(phone, country) if (phone_number and not is_possible_number(phone_number) or not phone_number.is_valid()): raise ValidationError(_("The phone number entered is not valid."), code="invalid_phone_number") return phone_number
def _create_user(self, username, email, password, phone="", **extra_fields): if not username: raise ValueError( "The given username must be set") # pragma: no cover phone_verified = False email_verified = False phone_parsed = to_python(username) if phone_parsed.is_valid(): phone = phone_parsed username = str(phone) phone_verified = True elif "@" in username: email = username username = self.normalize_email(email) email_verified = True user = super()._create_user(username, email, password, phone=phone, email_verified=email_verified, phone_verified=phone_verified, **extra_fields) return user
def decompress(self, value): if value: if isinstance(value, unicode): value = to_python(value) if isinstance(value, PhoneNumber): return u'+%d' % value.country_code, value.national_number return [None, None]
def update(self, instance, validated_data): phone = validated_data.pop('profile', {}).pop('phone', None) if phone and to_python(phone).is_valid(): profile = instance.profile profile.phone = phone profile.save() return super(UserSerializer, self).update(instance, validated_data)
def __set__(self, instance, value): value = to_python(value) or "" if instance.__dict__.get(self.field.name) != value: instance.__dict__[self.field.name] = value instance.__dict__[ self.validation_field_name] = self.unverified_value
def validate_possible_number(phone, country=None): phone_number = to_python(phone, country) if (phone_number and not is_possible_number(phone_number) or not phone_number.is_valid()): raise ValidationError("The phone number entered is not valid.", code=AccountErrorCode.INVALID) return phone_number
def add_user(request): ''' register a user ''' uname = request.POST[ 'username' ] email = request.POST[ 'email' ] psw = request.POST[ 'password' ] re_psw = request.POST[ 're_paw' ] phone = to_python( request.POST[ 'phone' ] ) description = request.POST[ 'description' ] error = '' if len(uname) == 0: error = u'请输入用户名' elif len( email ) == 0 or not is_valid_email( email ): error = u'请输入正确的邮箱' elif cmp( psw, re_psw ) != 0: error = u'两次密码输入不一致' elif not phone.is_valid(): error = u'请输入正确的电话号码(例如+8613012345678)' else: user = User.objects.create_user( uname, email, psw ) usr_exd = UsrExd( user=user, phone_number=phone, description=description ) usr_exd.save() error = u'注册成功' return render_to_response( 'person.html', { 'username':uname, 'email':email, 'phone':str(phone), 'description':description, 'user':request.user, 'error':error }, context_instance=RequestContext(request) );
def to_representation(self, value): phonenumber = to_python(value) if phonenumber.is_valid(): p = str(phonenumber) if p.startswith("+") and self.remove_plus: return p[1:] # remove leading + else: return p
def get_prep_value(self, value): "Returns field's value prepared for saving into a database." if not value: if not self.blank: return to_python(self.default) elif self.blank: return to_python(self.default) or '' if value != '': value = to_python(value) if isinstance(value, string_types): # it is an invalid phone number return value format_string = getattr(settings, 'PHONENUMBER_DB_FORMAT', 'E164') fmt = PhoneNumber.format_map[format_string] return value.format_as(fmt)
def match(self, name, phone): phone = to_python(phone) phone_matches = UserProfile.objects.filter(phone=phone) if phone_matches.count(): return phone_matches[0] return None
def get_prep_value(self, value): "Returns field's value prepared for saving into a database." if value is None or value == '': if not self.blank: return to_python(self.default) elif self.blank: return to_python(self.default) or '' if value != '': value = to_python(value) if isinstance(value, string_types): # it is an invalid phone number return value format_string = getattr(settings, 'PHONENUMBER_DB_FORMAT', 'E164') fmt = PhoneNumber.format_map[format_string] return value.format_as(fmt)
def validate_couple_request(self, request_sender, request_receiver): request_sender = to_python(request_sender) request_receiver = to_python(request_receiver) user = self.user if Couple.objects.filter(Q(partner_a=user) | Q(partner_b=user)): return False, _(u"이미 커플로 등록된 이메일입니다.") if request_sender is None or request_receiver is None: return False, _(u"전화번호를 입력해주세요.") if not request_sender.is_valid() and not request_receiver.is_valid(): return False, _(u"전화번호를 다시 한 번 확인해주세요.") if request_sender == request_receiver: return False, _(u"전화번호를 다시 한 번 확인해주세요.") return True, None
def validate_phone_or_email(value): phone_number = to_python(value) error = ValidationError(_( "The Phone number or Email entered is not valid. Phone number must have international format!" ), code="invalid_phone_number_or_email") if not phone_number.is_valid(): if validate_email(value) != None: raise error
def to_python(self, value): phone_number = to_python(value, region=self.region) if phone_number in validators.EMPTY_VALUES: return self.empty_value if phone_number and not phone_number.is_valid(): raise ValidationError(self.error_messages["invalid"]) return phone_number
def clean(self, phones): normalized_phones = list(OrderedDict.fromkeys(normalize_phone_number(phone) for phone in phones if normalize_phone_number(phone))) invalid_phones = [phone for phone in normalized_phones if not phonenumber.to_python(phone).is_valid()] if invalid_phones: raise ValidationError(self.default_error_messages['invalid_phones'].format(', '.join(invalid_phones))) if not normalized_phones and self.required: raise ValidationError(self.default_error_messages['required']) return normalized_phones
def __call__(self, value): queryset = self.queryset queryset = self.filter_queryset(value, queryset) queryset = self.exclude_current_instance(queryset) if qs_exists(queryset): raise ve2(self.message, code='unique') phone_number = to_python(value) if phone_number and not phone_number.is_valid(): raise ve1(_('The phone number entered is not valid.'), code='invalid_phone_number')
def get_prep_value(self, value): """Returns field's value prepared for saving into a database.""" if not value: if self.default is not NOT_PROVIDED: return to_python(self.default) elif self.null: return None else: # returns empty string even if blank is False # blank should be handled at form level return '' else: value = to_python(value) if isinstance(value, string_types): # it is an invalid phone number return value format_string = getattr(settings, 'PHONENUMBER_DB_FORMAT', 'E164') fmt = PhoneNumber.format_map[format_string] return value.format_as(fmt)
def get_prep_value(self, value): """ Perform preliminary non-db specific value checks and conversions. """ value = super(PhoneNumberField, self).get_prep_value(value) value = to_python(value) if not isinstance(value, PhoneNumber): return value format_string = getattr(settings, 'PHONENUMBER_DB_FORMAT', 'E164') fmt = PhoneNumber.format_map[format_string] return value.format_as(fmt)
def get_prep_value(self, value): """ Perform preliminary non-db specific value checks and conversions. """ value = super(PhoneNumberField, self).get_prep_value(value) value = to_python(value) if not isinstance(value, PhoneNumber): return value format_string = getattr(settings, "PHONENUMBER_DB_FORMAT", "E164") fmt = PhoneNumber.format_map[format_string] return value.format_as(fmt)
def serializer_custom_validate_international_phonenumber(value): value = re.sub('[ -]', '', value) if value.startswith('+') is False: if len(value) == 10: value = "+1%s" % value elif len(value) == 11: value = "+%s" % value phone_number = to_python(value) if phone_number and not phone_number.is_valid(): raise ValidationError(_('The phone number entered is not valid.'))
def to_python(self, value, *args, **kwargs): """ Convert value from National US phone number to international """ phone_number = to_python(value) # Check if phone number returned, and if it's valid. If invalid, check # for the reason to return the specific error message or the default if phone_number is None: return phone_number if phone_number and not phone_number.is_valid(): reason = is_possible_number_with_reason(phone_number) raise exceptions.ValidationError( self.error_messages.get(reason, self.error_messages['invalid']) ) return phone_number
def _generate_valid_phone(): """Sometimes, FactoryFaker generates a phone number that PhoneNumberField does not consider valid which makes tests to randomly fail. This function always generate a valid french phone number for PhoneNumberField""" for try_attempt in range(10): phone = Faker("fr_FR").phone_number() if to_python(phone, settings.PHONENUMBER_DEFAULT_REGION).is_valid(): break else: raise ValidationError( "Couldn't generate a valid phone number for PhoneNumberField") return phone
def prepare_value(self, value): if self.region and value not in validators.EMPTY_VALUES: phone_number = (value if isinstance(value, PhoneNumber) else to_python(value, region=self.region)) try: phone_region_codes = phonenumbers.data._COUNTRY_CODE_TO_REGION_CODE[ phone_number.country_code] except KeyError: pass else: if self.region in phone_region_codes: value = phone_number.as_national return value
def to_python(self, value): phone_number = to_python(value, region=self.region) if phone_number in validators.EMPTY_VALUES: return self.empty_value if phone_number and not phone_number.is_valid(): if self.region == "FR": # As django-phonenumber-field does not support validation of # french overseas territories numbers when region defaults to 'FR', # we try to validate the phone number against all these territories # country codes to see if one matches before returning a validation # error. for country_code in FRENCH_COUNTRY_CODES: phone_number = to_python(value, country_code) if phone_number.is_valid(): self.region = country_code return phone_number raise ValidationError(self.error_messages["invalid"]) return phone_number
def generate_login_token(phone, next=""): sha = hashlib.sha1() sha.update(settings.SECRET_KEY) sha.update(str(to_python(phone))) sha.update(randomword(20)) token = sha.hexdigest() login_token = LoginToken.objects.create(token=token, phone=phone, next_url=next) return login_token
def match_or_create(self, name=None, phone=None): phone = to_python(phone) user = self.match(name, phone) created = False if not user: created = True user = UserProfile.objects.create(phone, name=name) user.set_password("nopassword") user.newly_created = True user.save(using=self._db) return user, created
def test_prep_value(self): """ Tests correct db storage value against different setting of PHONENUMBER_DB_FORMAT Required output format is set as string constant to guarantee consistent database storage values """ number = PhoneNumberField() for frmt in ["E164", "RFC3966", "INTERNATIONAL"]: with override_settings(PHONENUMBER_DB_FORMAT=frmt): self.assertEqual( number.get_prep_value(to_python(self.storage_numbers[frmt][0])), self.storage_numbers[frmt][1], )
def clean(self, value, previous_values): if value: if self.event.settings.region in SUPPORTED_REGIONS: region = self.event.settings.region elif self.event.settings.locale[:2].upper() in SUPPORTED_REGIONS: region = self.event.settings.locale[:2].upper() else: region = None phone_number = to_python(value, region) if not phone_number or not phone_number.is_valid(): raise ValidationError(_('Enter a valid phone number.')) return phone_number return value
def clean_username(self): username = self.cleaned_data["username"] any_valid = False phone_number = to_python(username) if phone_number.is_valid(): if phone_number.is_mobile(): return username else: raise ValidationError("Please provide a mobile number") # Not a phone number, assume email validate_email(username) return username
def get_prep_value(self, value): """ Perform preliminary non-db specific value checks and conversions. """ if value: if not isinstance(value, PhoneNumber): value = to_python(value) if not value.is_valid(): raise ValueError("“%s” is not a valid phone number." % value.raw_input) format_string = getattr(settings, "PHONENUMBER_DB_FORMAT", "E164") fmt = PhoneNumber.format_map[format_string] value = value.format_as(fmt) return super(PhoneNumberField, self).get_prep_value(value)
def get_prep_value(self, value): """ Perform preliminary non-db specific value checks and conversions. """ if value: if not isinstance(value, PhoneNumber): value = to_python(value) if value.is_valid(): format_string = getattr(settings, "PHONENUMBER_DB_FORMAT", "E164") fmt = PhoneNumber.format_map[format_string] value = value.format_as(fmt) else: value = self.get_default() return super(PhoneNumberField, self).get_prep_value(value)
def get_prep_value(self, value): """ Perform preliminary non-db specific value checks and conversions. """ if value: if not isinstance(value, PhoneNumber): value = to_python(value) if not value.is_valid(): raise ValueError("“%s” is not a valid phone number." % value.raw_input) format_string = getattr(settings, "PHONENUMBER_DB_FORMAT", "E164") fmt = PhoneNumber.format_map[format_string] value = value.format_as(fmt) return super().get_prep_value(value)
def test_prep_value(self): ''' Tests correct db storage value against different setting of PHONENUMBER_DB_FORMAT Required output format is set as string constant to guarantee consistent database storage values ''' number = PhoneNumberField() old_format = getattr(settings, 'PHONENUMBER_DB_FORMAT', 'E164') for frmt in ['E164', 'RFC3966', 'INTERNATIONAL']: setattr(settings, 'PHONENUMBER_DB_FORMAT', frmt) self.assertEqual( number.get_prep_value(to_python( self.storage_numbers[frmt][0])), self.storage_numbers[frmt][1]) setattr(settings, 'PHONENUMBER_DB_FORMAT', old_format)
def phonenumber_validation(data): """ Validates phonenumber Similar to phonenumber_field.validators.validate_international_phonenumber() but uses a different message if the country prefix is absent. """ from phonenumber_field.phonenumber import to_python phone_number = to_python(data) if not phone_number: return data elif not phone_number.country_code: raise serializers.ValidationError(_("Phone number needs to include valid country code (E.g +37255555555)")) elif not phone_number.is_valid(): raise serializers.ValidationError(_('The phone number entered is not valid.')) return data
def test_prep_value(self): ''' Tests correct db storage value against different setting of PHONENUMBER_DB_FORMAT Required output format is set as string constant to guarantee consistent database storage values ''' number = PhoneNumberField() old_format = getattr(settings, 'PHONENUMBER_DB_FORMAT', 'E164') for frmt in ['E164', 'RFC3966', 'INTERNATIONAL']: setattr(settings, 'PHONENUMBER_DB_FORMAT', frmt) self.assertEqual( number.get_prep_value( to_python(self.storage_numbers[frmt][0]) ), self.storage_numbers[frmt][1]) setattr(settings, 'PHONENUMBER_DB_FORMAT', old_format)
def clean_username(self): """ Find user and return his username Applicant can auth by email or phone, so we try find user by email or phone if we found him we return his username for future auth """ username = to_python(self.cleaned_data['username']) applicant = models.Applicant.objects.filter(Q(email=username) | Q(phone=username)).first() if applicant is not None: return applicant.username employer = models.Employer.objects.filter(Q(email=username) | Q(phone=username)).first() if employer is not None: return employer.username return self.cleaned_data['username']
def phonenumber_validation(data): """ Validates phonenumber Similar to phonenumber_field.validators.validate_international_phonenumber() but uses a different message if the country prefix is absent. """ from phonenumber_field.phonenumber import to_python phone_number = to_python(data) if not phone_number: return data elif not phone_number.country_code: raise serializers.ValidationError( _("Phone number needs to include valid country code (E.g +37255555555)" )) elif not phone_number.is_valid(): raise serializers.ValidationError( _('The phone number entered is not valid.')) return data
def change_user( request ): ''' change the information if the user ''' check = check_user( request ) if check: return check user = User.objects.get( username__exact = request.user.username ) psw = request.POST[ 'password' ] re_psw = request.POST[ 're_paw' ] email = request.POST[ 'email' ] phone = to_python( request.POST[ 'phone' ] ) description = request.POST[ 'description' ] error = '' if ( len(psw) > 0 ) and ( cmp( psw, re_psw ) == 0 ): user.set_password( psw ) if cmp( psw, re_psw ) != 0: error = u'两次密码输入不一致' if len(email) != 0 and email_re.match( email ): user.email = email else: error = u'请输入正确的邮箱' if not phone.is_valid(): error = u'请输入正确的电话号码(例如+8613012345678)' else: user.usrexd.phone_number = phone user.usrexd.description = description user.save() user.usrexd.save() if not error: error = u'成功修改个人信息' return render_to_response( 'person.html', { 'username':user.username, 'email':user.email, 'user':request.user, 'phone':user.usrexd.phone_number, 'description':user.usrexd.description, 'error':error }, context_instance=RequestContext(request) );
def authenticate(self, request, username=None, password=None, **kwargs): if username is None: username = kwargs.get(User.USERNAME_FIELD) if username is None or password is None: return phone = to_python(username) if phone and phone.is_valid(): try: user = User.objects.get(phone=phone) except User.DoesNotExist: User().set_password(password) else: if user.check_password( password) and self.user_can_authenticate(user): return user else: return super(EmailPhoneBackend, self).authenticate(request, username=username, password=password, **kwargs)
def __set__(self, instance, value): instance.__dict__[self.field_name] = to_python(value)
def validate_possible_number(value): phone_number = to_python(value) if phone_number and not is_possible_number(phone_number): raise ValidationError( _('The phone number entered is not valid.'), code='invalid_phone_number')
def to_python(self, value): phone_number = to_python(value) if phone_number and not phone_number.is_valid(): raise ValidationError(self.error_messages['invalid']) return phone_number
def __set__(self, instance, value): instance.__dict__[self.field.name] = to_python(value, region=self.field.region)
def validate_international_phonenumber(value): phone_number = to_python(value) if phone_number and not phone_number.is_valid(): raise ValidationError(_(u'The phone number entered is not valid.'))
def to_internal_value(self, data): phone_number = to_python(data) if phone_number and not phone_number.is_valid(): raise ValidationError(self.error_messages["invalid"]) return phone_number
def test_does_not_fail_on_invalid_values(self): # testcase for # https://github.com/stefanfoulis/django-phonenumber-field/issues/11 phone = to_python(42) self.assertEqual(phone, None)
def test_raise_on_invalid_values(self): msg = "Can't convert int to PhoneNumber." with self.assertRaisesMessage(TypeError, msg): to_python(42)
def validate_international_phonenumber(value): phone_number = to_python(value) if phone_number and not phone_number.is_valid(): raise ValidationError(_(u'Enter a valid phone number ("e.g +411234567").'))
def validate_international_phonenumber(value): phone_number = to_python(value) if phone_number and not phone_number.is_valid(): raise ValidationError(validate_international_phonenumber.message, code='invalid')