Пример #1
0
 def get_phone_and_phone_cc(client_phone, country_code):
     """
     Parse the contact phone number
     :param client_phone: the phone number added by the client
     :param country_code: eg.: 'RO', 'IT',..
     :return: returns the client national phone number and it's phone country code
     """
     phone_cc = None
     try:
         parsed_phone = phonenumbers.parse(client_phone)
         phone_cc = parsed_phone.country_code
         phone = parsed_phone.national_number
     except Exception as e:
         LOG.debug(e)
         if client_phone[
                 0] != '+':  # number misses country code, determine it then add the national number
             for ph_cc, country_c in COUNTRY_CODE_TO_REGION_CODE.items():
                 if country_code in country_c:
                     phone_cc = ph_cc
                     break
             parsed_phone = phonenumbers.parse('+{}{}'.format(
                 phone_cc, client_phone))
             phone = parsed_phone.national_number
         else:
             raise e
     return phone, phone_cc
Пример #2
0
def upgrade():
    data = []
    for country_code, iso_codes in COUNTRY_CODE_TO_REGION_CODE.items():
        if country_code not in COUNTRY_CODES_FOR_NON_GEO_REGIONS:
            for iso_code in iso_codes:
                data.append({
                    "iso_code": iso_code,
                    "country_code": country_code
                })
    op.bulk_insert(country, data)
Пример #3
0
def phonenumber_validation_view(request):
    phone_number = request.GET.get("phone", "").replace(" ", "")
    country_code = "DE"  # DEFAULT
    for region_code, country_code_list in COUNTRY_CODE_TO_REGION_CODE.items():
        prefix = f"+{region_code}"
        if phone_number.startswith(prefix):
            country_code = country_code_list[0]
            break
    formater = phonenumbers.AsYouTypeFormatter(country_code)
    result = ""
    for digit in phone_number:
        result = formater.input_digit(digit)
    return JsonResponse(data={
        "phone": result,
        "country_code": country_code
    },
                        status=201,
                        safe=False)
Пример #4
0
class UpdatePhoneForm(FlaskForm):
    choices = []
    for code, countries in COUNTRY_CODE_TO_REGION_CODE.items():
        for country in countries:
            try:
                choices.append('+' + str(code) + ' ' +
                               pycountry.countries.get(alpha_2=country).name)
            except AttributeError:
                pass
    choices = [choice.split(',')[0] for choice in choices]

    country = SelectField('Country code',
                          validators=[DataRequired()],
                          choices=choices)
    phone = StringField('Your phone number',
                        validators=[DataRequired(),
                                    Length(max=20)])
    public = BooleanField('Allow', default='checked')
    submit = SubmitField('Submit')
Пример #5
0
class Profile(models.Model):
    choices = []
    for code, countries in COUNTRY_CODE_TO_REGION_CODE.items():
        for country in countries: 
            try:
                choices.append([
                    '+' + str(code),
                    '+' + str(code) + ' ' + pycountry.countries.get(alpha_2 = country).name
                ])
            except AttributeError:
                pass
    choices = [[None, '']] + [[i, j.split(',')[0]] for i, j in choices]
                

    user = models.OneToOneField(User, on_delete = models.CASCADE)

    id = models.BigAutoField(primary_key = True, default = gen_key)
    created_at_ip = models.GenericIPAddressField(null = True, blank = True)
    handle = models.TextField(
        default = gen_hex,
        unique = True, 
        error_messages={
            'unique': 'That username has been taken. Please choose another.'
        }
    )
    country_code = models.CharField(max_length = 200, null = True, choices = choices)
    phone = models.CharField(max_length = 20, null = True, blank = True, unique = True)
    phone_public = models.BooleanField(default = True)
    birthdate = models.DateField(null = True, blank = True)

    profile_image = models.ImageField(default = 'default_profile.png', upload_to = 'profile_pics')
    background_image = models.ImageField(default = 'default_background.png', upload_to = 'background_pics')
    bio = models.TextField(max_length = 160, null = True, blank = True)
    location = models.TextField(max_length = 30, null = True, blank = True)
    website = models.URLField(max_length = 100, null = True, blank = True)

    following = models.ManyToManyField(
        'self', 
        symmetrical = False,
        through = 'Following',
        # through_fields = ('profile', 'profile')     # not needed to itself w/ 2 ForeignKey
    )

    last_checked_message_at = DateTimeField(default = timezone.now)

    @property
    def new_message(self):
        if len(self.received.all()) == 0:
            return False
        elif self.received.order_by('-created_at').first().created_at > self.last_checked_message_at:
            return True

    @property
    def follow_recommendation(self):
        recommendation = Profile.objects.exclude(
            Q(handle__in = self.following.values('handle')) |
            Q(handle = self.handle)
        ).order_by('?')[:3]
        return recommendation


    # disable to avoid PIL conflict with s3
    # will do it through s3 lambda
    # override save() in the Model class
    # def save(self, *args, **kwargs):
    #     super().save(*args, **kwargs)                                                      # first run the parent's save method
    #     output_size = {'profile': (400, 400), 'background': (600, 200)}
    #     p_img = Image.open(self.profile_image.path)
    #     b_img = Image.open(self.background_image.path)

    #     if p_img.width > 400 or p_img.height > 400:
    #         p_img.thumbnail(output_size.get('profile'))
    #         p_img.save(self.profile_image.path)

    #     if b_img.width > 600 or p_img.height > 200:
    #         b_img.thumbnail(output_size.get('background'))
    #         b_img.save(self.background_image.path)

    def __repr__(self):
        return f'{self.user.username.title()}'

    def __str__(self):
        return f'{self.user.username.title()}'
Пример #6
0
def get_calling_code(iso):
    for code, isos in COUNTRY_CODE_TO_REGION_CODE.items():
        if iso.upper() in isos:
            return code
    return None
Пример #7
0
from django.forms import Select, TextInput
from phonenumber_field.widgets import PhoneNumberPrefixWidget
from phonenumbers import COUNTRY_CODE_TO_REGION_CODE

phone_prefixes = [('+{}'.format(k), '+{}'.format(k))
                  for (k, v) in sorted(COUNTRY_CODE_TO_REGION_CODE.items())]


class PhonePrefixWidget(PhoneNumberPrefixWidget):
    """Uses choices with tuple in a simple form of "+XYZ: +XYZ".

    Workaround for an issue:
    https://github.com/stefanfoulis/django-phonenumber-field/issues/82
    """

    template_name = 'account/snippets/phone_prefix_widget.html'

    def __init__(self, attrs=None):
        widgets = (Select(attrs=attrs, choices=phone_prefixes), TextInput())
        # pylint: disable=bad-super-call
        super(PhoneNumberPrefixWidget, self).__init__(widgets, attrs)


class DatalistTextWidget(Select):
    template_name = "account/snippets/datalist.html"
    input_type = "text"

    def get_context(self, *args):
        context = super(DatalistTextWidget, self).get_context(*args)
        context['widget']['type'] = self.input_type
        return context
Пример #8
0
class AddressForm(ModelForm):
    class Meta:
        model = Address
        fields = [
            'addressee', 'street', 'apt', 'city', 'state', 'zip_code',
            'country', 'phone', 'phone_prefix', 'email'
        ]
        widgets = {
            'addressee':
            TextInput(attrs={
                'required': "true",
                "id": "recip",
                "class": "address-field"
            }),
            'street':
            TextInput(
                attrs={
                    'id': 'autocomplete',
                    'class': 'input-field col mods field address-field',
                    'required': "true"
                }),
            'city':
            TextInput(
                attrs={
                    'class': 'input-field col mods field address-field',
                    'id': 'locality',
                    'required': "true"
                }),
            'state':
            TextInput(
                attrs={
                    'class': 'input-field col mods field address-field',
                    'id': 'administrative_area_level_1',
                    'required': "true"
                }),
            'zip_code':
            TextInput(
                attrs={
                    'class': 'input-field col mods address-field',
                    'id': 'postal_code',
                    'required': "true"
                }),
            'phone':
            TextInput(attrs={
                'class': 'input-field col mods',
                'id': 'phone'
            }),
            'phone_prefix':
            Select(attrs={
                'class': 'input-field col mods',
                'id': 'phone-prefix'
            }),
            'email':
            TextInput(
                attrs={
                    'class': 'input-field col mods address-field',
                    'id': 'email',
                    'required': "true"
                }),
            'apt':
            TextInput(attrs={
                'class': 'input-field col mods',
                'id': 'apt'
            })
        }

    phone_prefix = ChoiceField(
        choices=[('+{}'.format(key), '+{} ({})'.format(key, value[0]))
                 for key, value in COUNTRY_CODE_TO_REGION_CODE.items()])
Пример #9
0
from django.forms import Select, TextInput
from phonenumber_field.widgets import PhoneNumberPrefixWidget
from phonenumbers import COUNTRY_CODE_TO_REGION_CODE

phone_prefixes = [
    ("+{}".format(k), "+{}".format(k))
    for (k, v) in sorted(COUNTRY_CODE_TO_REGION_CODE.items())
]


class PhonePrefixWidget(PhoneNumberPrefixWidget):
    """Uses choices with tuple in a simple form of "+XYZ: +XYZ".

    Workaround for an issue:
    https://github.com/stefanfoulis/django-phonenumber-field/issues/82
    """

    template_name = "account/snippets/phone_prefix_widget.html"

    def __init__(self, attrs=None):
        widgets = (Select(attrs=attrs, choices=phone_prefixes), TextInput())
        # pylint: disable=bad-super-call
        super(PhoneNumberPrefixWidget, self).__init__(widgets, attrs)

    def value_from_datadict(self, data, files, name):
        value = super().value_from_datadict(data, files, name)
        # FIXME: this is a hack, we should not be using a multiwidget
        # in forms used by the API but here we are
        if not value and name in data:
            value = data[name]
        return value
Пример #10
0
 def phone_prefix(self):
     for code, isos in COUNTRY_CODE_TO_REGION_CODE.items():
         if self.code in isos:
             return '+' + str(code)
     return None