Coder Social home page Coder Social logo

django-phonenumber-field's Introduction

django-phonenumber-field

A Django library which interfaces with python-phonenumbers to validate, pretty print and convert phone numbers. python-phonenumbers is a port of Google's libphonenumber library, which powers Android's phone number handling.

Documentation

https://django-phonenumber-field.readthedocs.io/

Running tests

tox needs to be installed. To run the whole test matrix with the locally available Python interpreters and generate a combined coverage report:

tox

run a specific combination:

tox -e py310-djmain,py39-djmain

django-phonenumber-field's People

Contributors

adamchainz avatar amateja avatar andreleitaodeveloper avatar ari-gen-x avatar ashleyredzko avatar dependabot[bot] avatar francoisfreitag avatar garetjax avatar hanwentao avatar hwkns avatar interdist avatar jambonrose avatar jdufresne avatar jeffbowen avatar jose-flores avatar kevin-brown avatar lampslave avatar lfrodrigues avatar maiksprenger avatar nferrari avatar phillipuniverse avatar punkyoon avatar romantolkachyov avatar scop avatar srax47 avatar stefanfoulis avatar tdobrovolny avatar thedrow avatar themarcq avatar vbabiy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-phonenumber-field's Issues

object has no attribute 'model'

I'm declaring it like this in my form class:

phone = PhoneNumberField(blank=True)

In my template I use this:

{{form.phone}}

And I get the error in my debug mode:

'PhoneNumberField' object has no attribute 'model'

Is there anything i'm doing wrong here?

django>=1.5 should be added to install_requires

There doesn't seem to be any listing for django in the setup.py file. I'm not sure which versions this library works with, but the Travis files seem to indicate that it's only being tested with Django 1.5 and greater. So, setup.py should probably match what's being covered by testing.

Impossible to set PhoneNumberField to None/null

tl;dr: Given the current implementation of the field, it is impossible to set the field to the database null value.

In the current implementation, an empty PhoneNumberField field will always be set to the empty string. While Django recommends against using subclasses of CharField with the option null=True, this sometimes becomes necessary when the field is both optional and unique.

phone = PhoneNumberField(blank=True, default=None, null=True, unique=True)

In the case of an optional unique field, it becomes important to avoid the empty string, as this causes uniqueness IntegrityError to be raised. Instead, the use of null (or None in Python) become necessary, as null values do not cause uniqueness conflicts.

It is therefore important for the field to be able to support the ability to be set to None or null.

Extensions are silently stripped

Saving a value like "424-417-2469x61914" results in the value "+14244172469", with the extension removed, instead of either saving the extension or throwing an error.

Create a new 0.7 version?

The 0.6 version has some bugs (like'NoneType' object has no attribute 'as_e164') which are resolved in merges there after, but difficult to get the latest version from pip.

Can't run Django commands after using the widget

When the widget is in use in the admin, the babel Locale is imported.
The Django default locale: translation.get_language() is en-us.

In the admin I have configured the following:

formfield_overrides = {
PhoneNumberField: {'widget': PhoneNumberPrefixWidget(initial='NL'), }
}

Since I want to use an initial value for the country the PhonePrefixSelect is run.
This raises an error since Babel doesn't know the en-us locale.

Hence management commands die with this error:
UnknownLocaleError: unknown locale 'en-us'

AttributeError exception occurred when trying to generate doc by sphinx

5:17 PM

/vagrant/docs/reference/core/accounting.rst:29: WARNING: autodoc: failed to import attribute 'BaseProfile.phone_number' from module 'app_server.apps.core.accounting.models'; the following exception was raised:
Traceback (most recent call last):
File "/home/vagrant/.virtualenvs/app_server/lib/python3.4/site-packages/sphinx/util/inspect.py", line 109, in safe_getattr
return getattr(obj, name, *defargs)
File "/home/vagrant/.virtualenvs/app_server/lib/python3.4/site-packages/phonenumber_field/modelfields.py", line 33, in get
% (self.field.name, owner.name))
AttributeError: The 'phone_number' attribu
te can only be accessed from BaseProfile instances.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/home/vagrant/.virtualenvs/app_server/lib/python3.4/site-packages/sphinx/ext/autodoc.py", line 392, in import_object
obj = self.get_attr(obj, part)
File "/home/vagrant/.virtualenvs/app_server/lib/python3.4/site-packages/sphinx/ext/autodoc.py", line 288, in get_attr
return safe_getattr(obj, name, *defargs)
File "/home/vagrant/.virtualenvs/app_server/lib/python3.4/site-packages/sphinx/util/inspect.py", line 115, in safe_getattr
raise AttributeError(name)
AttributeError: phone_number
/vagrant/docs/reference/core/accounting.rst:29: WARNING: autodoc: failed to import attribute 'LegalProfile.phone_number' from module 'app_server.apps.core.accounting.models'; the following exception was raised:
Traceback (most recent call last):
File "/home/vagrant/.virtualenvs/app_server/lib/python3.4/site-packages/sphinx/util/inspect.py", line 109, in safe_getattr
return getattr(obj, name, *defargs)
File "/home/vagrant/.virtualenvs/app_server/lib/python3.4/site-packages/phonenumber_field/modelfields.py", line 33, in get
% (self.field.name, owner.name))
AttributeError: The 'phone_number' attribute can only be accessed from LegalProfile instances.

easier tests

  • make it easier to run testsuite locally
  • setup on travis
  • setup on coveralls.io

Not working with Model Mixin

If I use Django phonenumber-field directly then Django detects it and applies the migrations properly but If I use Django phonenumber-field with mixin (abstract model) then Django fails to detect the changes. Can you tell me how to fix this ???

global name 'self' is not defined

File "/home/mktums/Dev/adcleaner-new/crawler/spiders/arendakv/arendakv.py", line 69, in parse_item
    item = ArendaKV(**record)
File "/home/mktums/.envs/adcleaner-new/lib/python2.6/site-packages/django/db/models/base.py", line 354, in __init__
    setattr(self, field.attname, val)
File "/home/mktums/Dev/adcleaner-new/phonenumber_field/modelfields.py", line 37, in __set__
    instance.__dict__[self.field.name] = to_python(value)
File "/home/mktums/Dev/adcleaner-new/phonenumber_field/phonenumber.py", line 72, in to_python
    phone_number = self.field.attr_class()
exceptions.NameError: global name 'self' is not defined

Using last dev commit

No locale when installed with pip

After a pip install django-phonenumber-field
the installed package does not contain a locale/ directory.

I think recursive-include phonenumber_field/locale * is missing in MANIFEST.in.

Can't run South migration to add a PhoneNumberField

I'm adding a PhoneNumberField field (with blank=True) to an existing model. As such, when I run ./manage schemamigration --auto myapp, South demands that I provide a default value for the column it will be adding. If I set the default (either in models.py or as a one-off in the South migration) to "" (an empty string), when I try to run the migration I get an AttributeError:

AttributeError: 'NoneType' object has no attribute 'as_e164'

This is because in get_prep_value, the first if block is passed (since "" does not equal None) and the to_python function changes value from "" to None so when line 67 is hit, we get the AttributeError.

If I try setting the default to None, I then get an IntegrityError:

django.db.utils.IntegrityError: column "phone_number" contains null values

As the Django docs recommend and as mentioned in issue 1, we should use an empty string, not null, to represent a blank value for a CharField (which PhoneNumberField is under the hood). As such, although adding null=True to the field definition in my models makes the migration succeed, it leads to trouble down the road as you can end up with both "" and None as null values.

Not sure exactly how or where you'd like to change things but the request is that it be possible to have South work properly when defining a PhoneNumberField with blank=True. Let me know if I'm misunderstanding something here. Thanks!

PhonePrefixSelect breaks if no locale is active

It is possible that PhonePrefixSelect gets instantiated when there is no active locale. For example, i18n is deactivated by default in management commands.

Since Django 1.8, django.utils.translation.get_language returns None in this case:
https://docs.djangoproject.com/en/1.9/ref/utils/#django.utils.translation.get_language

This will then break on django.utils.translation.to_locale. Here is an example traceback:

(env)temha:~/development/center$ python manage.py createsuperuser
Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/home/temha/development/center/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line
    utility.execute()
  File "/home/temha/development/center/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 345, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/temha/development/center/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 348, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/temha/development/center/env/local/lib/python2.7/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 52, in execute
    return super(Command, self).execute(*args, **options)
  File "/home/temha/development/center/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 398, in execute
    self.check()
  File "/home/temha/development/center/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 426, in check
    include_deployment_checks=include_deployment_checks,
  File "/home/temha/development/center/env/local/lib/python2.7/site-packages/django/core/checks/registry.py", line 75, in run_checks
    new_errors = check(app_configs=app_configs)
  File "/home/temha/development/center/env/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 10, in check_url_config
    return check_resolver(resolver)
  File "/home/temha/development/center/env/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 19, in check_resolver
    for pattern in resolver.url_patterns:
  File "/home/temha/development/center/env/local/lib/python2.7/site-packages/django/utils/functional.py", line 33, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/temha/development/center/env/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 417, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "/home/temha/development/center/env/local/lib/python2.7/site-packages/django/utils/functional.py", line 33, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/temha/development/center/env/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 410, in urlconf_module
    return import_module(self.urlconf_name)
  File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/home/temha/development/center/center/urls.py", line 24, in <module>
    url(r'^accounts/', include('useraccount.urls')),
  File "/home/temha/development/center/env/local/lib/python2.7/site-packages/django/conf/urls/__init__.py", line 52, in include
    urlconf_module = import_module(urlconf_module)
  File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/home/temha/development/center/useraccount/urls.py", line 18, in <module>
    from useraccount.views import login, logout, signup
  File "/home/temha/development/center/useraccount/views.py", line 11, in <module>
    from useraccount.forms import *
  File "/home/temha/development/center/useraccount/forms.py", line 39, in <module>
    class UserAccountProfileForm(ModelForm):
  File "/home/temha/development/center/useraccount/forms.py", line 40, in UserAccountProfileForm
    class Meta:
  File "/home/temha/development/center/useraccount/forms.py", line 44, in Meta
    'phone' : PhoneNumberPrefixWidget(),
  File "/home/temha/development/center/env/local/lib/python2.7/site-packages/phonenumber_field/widgets.py", line 44, in __init__
    widgets = (PhonePrefixSelect(initial), TextInput(),)
  File "/home/temha/development/center/env/local/lib/python2.7/site-packages/phonenumber_field/widgets.py", line 20, in __init__
    locale = Locale(translation.to_locale(translation.get_language()))
  File "/home/temha/development/center/env/local/lib/python2.7/site-packages/django/utils/translation/__init__.py", line 188, in to_locale
    return _trans.to_locale(language)
  File "/home/temha/development/center/env/local/lib/python2.7/site-packages/django/utils/translation/trans_real.py", line 71, in to_locale
    p = language.find('-')
AttributeError: 'NoneType' object has no attribute 'find'

Maybe this could be fixed by checking for a None return value from get_language and falling back to settings.LANGUAGE_CODE in this case? This would effectively emulate the behaviour of Django < 1.8.

Extra documentation for the use of the widget

Could you expand the readme?
I had problems getting a form with the widget to work.

Something like this:

To use the widget in a form with an initial country:

class PhoneForm(forms.Form):
    telephone = PhoneNumberField(
        widget=PhoneNumberPrefixWidget(initial='NL'),
        required=False,
    )

And to pass initial data to the form use the following code, when we have a user with
a telephone field:

        data = {'telephone_0': '+%d' % user.telephone.country_code,
                    'telephone_1': user.telephone.national_number}
        form = PhoneForm(data)

can not query by None

The field does not appear to respect querying by "None".

class Number(models.Model):
...
    load = PhoneNumberField(
        null=True,
        blank=True,
    )

...


In [7]: ns = Number.objects.exclude(load=None).order_by('load')

In [8]: for n in ns:                                           
    print n.load.as_e164
   ...:     
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-8-28ccf03f2ed2> in <module>()
      1 for n in ns:
----> 2     print n.load.as_e164
      3 

AttributeError: 'NoneType' object has no attribute 'as_e164'

In [9]: 

Enter Valid Phone Number Form Error

I keep getting this form error even though I have formatted my number in the following ways:

+1 01 212 555-2345
+1 01 212 5552345
+15552345
15552345
5552345
212 555 2345
2125552345

This is my model:

class Contact(models.Model):
phone = PhoneNumberField(blank=True)

This is my Form:

class ExpForm(forms.Form):
phone = PhoneNumberField()

And this is my template for phone:

                           <div  id="phone" class="form_field">
            {{ form.phone.errors }}
            <label>{{ form.phone.label_tag }}</label>
            {{ form.phone }}
            </div>

How are the numbers supposed to be formatted for the Form fields?
I couldn't find any examples.

Widget initial by label, not value (country code US does not initialize as United States)

I am trying to set the initial value of the Prefix select, the issue is that when using initial='US' the select defaults to "American Samoa" because it is the first item in the list with the value of "+1", rather than "United States".

Is there a way to set the initial value based on the label rather than the value because of the duplicate country codes?

Issue with using PhoneNumberPrefixWidget in a formset

Thanks for the great work. Wonderful phone number field.

I was using this in a formset. And if the formset contains empty forms, django's default behavior is to short circuit any validation.

See https://github.com/django/django/blob/master/django/forms/forms.py#L373

But has_changed() is always returning true when using the PhoneNumberPrefixWidget, even if no values is submitted in the form.

I think the bug is here.

def value_from_datadict(self, data, files, name):
    values = super(PhoneNumberPrefixWidget, self).value_from_datadict(data, files, name)
    return '%s.%s' % tuple(values)

This code will return "." if values is None, so has_changed() is comparing "." with the initial value of the field, which is None, and is returning false because "." != None

I think the fix should be this.

def value_from_datadict(self, data, files, name):
    values = super(PhoneNumberPrefixWidget, self).value_from_datadict(data, files, name)
    if not any(values):
        return None
    return '%s.%s' % tuple(values)

local variable 'phone_number' referenced before assignment

Firstly, thank you for your library!

Within phonenumber_field/phonenumber.py there is the following function:

def to_python(value):
    if value in validators.EMPTY_VALUES:  # None or ''
        phone_number = None
    elif value and isinstance(value, basestring):
        try:
            phone_number = PhoneNumber.from_string(phone_number=value)
        except NumberParseException, e:
            # the string provided is not a valid PhoneNumber.
            phone_number = PhoneNumber(raw_input=value)
    elif isinstance(value, phonenumbers.phonenumber.PhoneNumber) and \
         not isinstance(value, PhoneNumber):
        phone_number = self.field.attr_class()
        phone_number.merge_from(value)
    elif isinstance(value, PhoneNumber):
        phone_number = value
    return phone_number

This can return phone_number without it being set. It might be good to add an else with a custom exception explaining why the else clause was reached otherwise there may be an error in the if / elif logic above.

New PyPI release

Now that the project is Python 3 compatible, it seems a new release (0.6?) to PyPI might be in order. What say you @stefanfoulis ?

unhashable type: 'PhoneNumber'

When I used PhoneNumberField(unique=True) I have got the error
"unhashable type: 'PhoneNumber'" because phonenumber_field.phonenumber.PhoneNumber doesn't implement hash method.

I used workaround

def PhoneNumberHash(self):
    return hash(self.as_e164)

PhoneNumber.__hash__ = PhoneNumberHash

and it fixes the problem, but it would be better to place this in the app's code

develop branch seems broken

Probably due to me merging multiple pull-requests that generated conflicts. Needs some thorough testing (tests!).

phonenumberslite fallback not working as intended

$ pip list | grep phonenumber
django-phonenumber-field (1.0.0)
phonenumbers (7.2.8)

$ grep phonenumber requirements.txt 
django-phonenumber-field~=1.1.0

$ pip install -Ur requirements.txt
[...]
Installing collected packages: phonenumberslite, django-phonenumber-field
  Running setup.py install for phonenumberslite ... done
  Found existing installation: django-phonenumber-field 1.0.0
    Uninstalling django-phonenumber-field-1.0.0:
      Successfully uninstalled django-phonenumber-field-1.0.0
Successfully installed django-phonenumber-field-1.1.0 phonenumberslite-7.2.8

So the full phonenumbers was already installed, but pip ended up installing phonenumberslite anyway. And now it's a bit of a mess, need to fix things manually (remove both phonenumberslite and phonenumbers and reinstall one of them).

Add note on 'PHONENUMBER_DEFAULT_REGION'

If there is a separate documentation website, then it'd be cool to show a link to it in the Readme.

If not, it'd be nice to document the 'PHONENUMBER_DEFAULT_REGION' feature. If you want me to, I can send a pull request with a modified Readme.

Thanks.

Python 3 support

I see a few PRs with this issue in mind:

#21
#29
#32

I was wondering if there is an agreed-upon goal or approach for introducing Python 3 support. I would be happy to help if I know the effort will not be in vain. :)

EDIT: I've submitted my own pull request now: #34

south field hints are buggy

The created south migrations import the field. That should not happen.
In the eyes of South it should just be a CharField.

PhoneNumberField with max_length of 128.

Hello Stefan :).

I was checking my migration and found that PhoneNumberField has max_legth of 128. I have found a bit weird this giant phone number size and since you are enforcing it and I had no tip checking commits I'm here asking why 128 instead something like 20 (1 for +, 3 for country code, 3 for area code, 13 for phone digits).

The code is at https://github.com/stefanfoulis/django-phonenumber-field/blame/develop/phonenumber_field/modelfields.py#L48

class PhoneNumberField(models.Field):
    attr_class = PhoneNumber
    descriptor_class = PhoneNumberDescriptor
    default_validators = [validate_international_phonenumber]

    description = _("Phone number")

    def __init__(self, *args, **kwargs):
        kwargs['max_length'] = kwargs.get('max_length', 128)
        super(PhoneNumberField, self).__init__(*args, **kwargs)
        self.validators.append(validators.MaxLengthValidator(self.max_length))

Thx man.

Wrong results while using '__in' field lookup

Given a Profile model with a PhoneNumberField called 'phone_number', if we have invalid phone numbers stores, such as:

obj = Profile()
obj.phone_number = 'foo'
obj.save()

Then we run a queryset using '__in':

Profile.objects.filter(phone_number__in=['bar'])

We get the object in the results.

It is a weird behavior, as the internal database field (I am using MySQL) is saved as a varchar. What is happening here?

Recommendation for usage within `django-localflavor`

Hey there,
The django-localflavor (https://github.com/django/django-localflavor) package is considering dropping all their phone number validations in favour of this package, because it's much more complete. Possibly in the next release we will add deprecation warnings, and then fully remove them in about a year.

I guess this is just a heads up, but I also just wanted to make sure that this was acceptable? It might increase the development burden on you and if this is a problem then please say. If it is not a problem then we could start to discuss ways to make the transition as easy as possible for existing users of the localflavor library?

Incorrect country displayed in PhoneNumberPrefixWidget select dropdown

Hello! Thanks for making a great library! We found a small bug-o. If I select a country with a country code that overlaps with another country, e.g.:

image

Then on save, the country code widget will display the country that has the same country code but appears first by sort order, e.g.,:

image

If the values of the PhoneNumberPrefixWidget's select element were the countries instead of the country codes, this issue would go away. Is there a workaround? If not, we can submit a PR to fix this. Thanks!

Phonenumber field difference for Python 2 and 3

Hi Guys,

Just a quick question.. why is that for Python 2, if the phone number is invalid it just returns the raw input while in Python 3, it converts it to either +NoneNone or +63(region code, mine is PH)(Raw Input) ?

Below are what i have tried.
Python2
print to_python('none') - none
print to_python('None') - None
print to_python('9581093') - 9581093
print PhoneNumber.from_string(phone_number='123') - 123

Python3
print(to_python('none')) - +NoneNone
print(to_python('None')) - +NoneNone
print(to_python('9581093')) - +639581093
print(PhoneNumber.from_string(phone_number='213')) - +63213

PhoneNumberPrefixWidget: 'PhoneNumber' object has no attribute 'split'

Hi,

While generating a form with PhoneNumberPrefixWidget I got a TraceBack.

Following test manages to reproduce it:

from django.test import TestCase

from phonenumber_field.widgets import PhoneNumberPrefixWidget
from phonenumber_field.phonenumber import PhoneNumber

class TestPhoneWidget(TestCase):

    def setUp(self):
        self.phone_number = PhoneNumber.from_string('+15550000')
        self.widget = PhoneNumberPrefixWidget()

    def testWidgetWorks(self):
        self.assertIsInstance(self.phone_number, PhoneNumber)
        self.assertTrue(self.widget.decompress(self.phone_number))

If you provide me some hints, I can implement decompress on PhoneNumber if it is the right thing to do.

Keep on the impressive work.
Kevin

No module named babel

When importing from widgets, I'm getting this error.
It's not listed in setup.py as a dependency, maybe that's why.

Can't set field to blank value once it has been populated

I am not sure if this is a bug or not, but I am having trouble getting the model to update the field to a blank value. The scenario is that when the record was created initially, a phone number was provided and correctly populated this field, but if I then go back and try to update that record and set the phone number field to blank ('') it will not take and does not get applied in the underlying model/database. The code works when you start with a blank value and then populate it, but what about starting with a populated field and try to remove the value? If someone provided a fax number, how do I update my record to a blank value if the end user no longer has a fax number? My scenario assumes the field has been defined only with blank=True and default='' similar to the fax_number field in your Basic Usage example.

Equal phonenumbers not equal

When you create two records with phonenumberfield, one with '+44 113 8921113' and other with '+441138921113' value and than compare them, they are not equal (comp_before is False).

class MandatoryPhoneNumber(models.Model):
    phone_number = PhoneNumberField()

first = MandatoryPhoneNumber.objects.create(phone_number='+44 113 8921113')
second = MandatoryPhoneNumber.objects.create(phone_number='+441138921113')

comp_before = first.phone_number == second.phone_number

first.save()
second.save()

first_db = MandatoryPhoneNumber.objects.get(id=first.id)
second_db = MandatoryPhoneNumber.objects.get(id=second.id)

comp_after = first_db.phone_number == second_db.phone_number

This is because parent class for PhoneNumberField compares in __eq__ function every attribute of phonenumber and for the '+44 113 8921113' and '+441138921113' differs raw_input attribute.

But when you save these two records to database and than read them from database, these two records are equal (comp_after is True), because we store phone number in database as string with constant format and initialize from database provided "normalized" string format.

And this is inconsistency - comp_before != comp_after. It must be comp_before == comp_after

Running migration on phonenumberfield results in AttributeError

I've got the straight up install of django-phonenumber-field, with phonenumberslite.
See extract from running pipdeptree below.

`django-phonenumber-field==1.1.0

  • phonenumberslite [required: >=7.0.2, installed: 7.3.1]
  • babel [installed: 2.3.3]
    • pytz [required: >=0a, installed: 2016.3]`

When I run manage.py migrate, I get

File "C:\Users\...\lib\site-packages\phonenumber_field\modelfields.py", line 76, in get_prep_value return value.format_as(fmt) AttributeError: 'NoneType' object has no attribute 'format_as'

as the last entry in the error trace.

I'm running Python 3.4.3
Any suggestion to what is causing this? How can I remedy as it is preventing my migrations from successfully running.

If blank=True, it's impossible to save an empty phone number

If you define a field like this in your models.py:

    faxnumber = PhoneNumberField(u'Fax',max_length=40,blank=True)

You'll have this backtrace:

Environment:


Request Method: POST
Request URL: http://morphee.hq.eyepea.be:8001/admin/xivo_web/entity/3/

Django Version: 1.3.1
Python Version: 2.5.2
Installed Applications:
['django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.admin',
 'xivo_web']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware')


Traceback:
File "/usr/lib/python2.5/site-packages/django/core/handlers/base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python2.5/site-packages/django/contrib/admin/options.py" in wrapper
  307.                 return self.admin_site.admin_view(view)(*args, **kwargs)
File "/usr/lib/python2.5/site-packages/django/utils/decorators.py" in _wrapped_view
  93.                     response = view_func(request, *args, **kwargs)
File "/usr/lib/python2.5/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
  79.         response = view_func(request, *args, **kwargs)
File "/usr/lib/python2.5/site-packages/django/contrib/admin/sites.py" in inner
  197.             return view(request, *args, **kwargs)
File "/usr/lib/python2.5/site-packages/django/utils/decorators.py" in _wrapper
  28.             return bound_func(*args, **kwargs)
File "/usr/lib/python2.5/site-packages/django/utils/decorators.py" in _wrapped_view
  93.                     response = view_func(request, *args, **kwargs)
File "/usr/lib/python2.5/site-packages/django/utils/decorators.py" in bound_func
  24.                 return func(self, *args2, **kwargs2)
File "/usr/lib/python2.5/site-packages/django/db/transaction.py" in inner
  217.                 res = func(*args, **kwargs)
File "/usr/lib/python2.5/site-packages/django/contrib/admin/options.py" in change_view
  982.                 self.save_model(request, new_object, form, change=True)
File "/usr/lib/python2.5/site-packages/django/contrib/admin/options.py" in save_model
  665.         obj.save()
File "/usr/lib/python2.5/site-packages/django/db/models/base.py" in save
  460.         self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File "/usr/lib/python2.5/site-packages/django/db/models/base.py" in save_base
  526.                         rows = manager.using(using).filter(pk=pk_val)._update(values)
File "/usr/lib/python2.5/site-packages/django/db/models/query.py" in _update
  491.         return query.get_compiler(self.db).execute_sql(None)
File "/usr/lib/python2.5/site-packages/django/db/models/sql/compiler.py" in execute_sql
  869.         cursor = super(SQLUpdateCompiler, self).execute_sql(result_type)
File "/usr/lib/python2.5/site-packages/django/db/models/sql/compiler.py" in execute_sql
  735.         cursor.execute(sql, params)
File "/usr/lib/python2.5/site-packages/django/db/backends/util.py" in execute
  34.             return self.cursor.execute(sql, params)
File "/usr/lib/python2.5/site-packages/django/db/backends/mysql/base.py" in execute
  86.             return self.cursor.execute(query, args)
File "/var/lib/python-support/python2.5/MySQLdb/cursors.py" in execute
  168.         if not self._defer_warnings: self._warning_check()
File "/var/lib/python-support/python2.5/MySQLdb/cursors.py" in _warning_check
  82.                     warn(w[-1], self.Warning, 3)
File "/usr/lib/python2.5/warnings.py" in warn
  62.                   globals)
File "/usr/lib/python2.5/warnings.py" in warn_explicit
  102.         raise message

Exception Type: Warning at /admin/xivo_web/entity/3/
Exception Value: Column 'faxnumber' cannot be null

PyPy3 Support

The current travis config tests on PyPy3. However, django-phonenumber-field depends on python-babel/babel , which does not currently support PyPy3, as noted in python-babel/babel#250 .

The error output by Travis is as follows:

Installed /home/travis/build/stefanfoulis/django-phonenumber-field
Processing dependencies for django-phonenumber-field==1.0.0
Searching for babel
Reading https://pypi.python.org/simple/babel/
Best match: Babel 2.2.0
Downloading https://pypi.python.org/packages/source/B/Babel/Babel-2.2.0.tar.gz#md5=1b69e4b2ab3795119266ccaa36b36f15
Processing Babel-2.2.0.tar.gz
Writing /tmp/easy_install-g7lzwt/Babel-2.2.0/setup.cfg
Running Babel-2.2.0/setup.py -q bdist_egg --dist-dir /tmp/easy_install-g7lzwt/Babel-2.2.0/egg-dist-tmp-om18us
Babel requires Python 2.6, 2.7 or 3.3+
error: Setup script exited with 1
The command "./.travis_setup" failed and exited with 1 during .

This appears to stem from the fact that PyPy3 announces itself as Python 3.2 .

$ source ~/virtualenv/pypy3/bin/activate
$ python --version
Python 3.2.5 (b2091e973da6, Oct 19 2014, 18:29:55)

python-babel/babel#171 has related information.

For the moment, for tests to pass, PyPy3 should be removed from testing on TravisCI.

Assign phonenumbers.phonenumber.PhoneNumber type to field raise TypeError

It is not possible to directly assign phonenumbers.phonenumber.PhoneNumber type to field because it raise TypeError: int() argument must be a string or a number, not 'PhoneNumber'.
This error is caused by trying cast phonenumbers.phonenumber.PhoneNumber object to field type object in to_python function.
phonenumbers.phonenumber.PhoneNumber does not support casting, because its constructor has as first argument country_code.
It must be prepared empty field and to this empty value must be merged wanted value by calling merge_from method.

pip install error

It is not currently possible to install via pip or git at the moment for me:

$ pip install django-phonenumber-field
Downloading/unpacking django-phonenumber-field
Could not find a version that satisfies the requirement django-phonenumber-field (from versions: 0.2a1, 0.2a3)
Cleaning up...
No distributions matching the version for django-phonenumber-field
Storing complete log in /Users/add/.pip/pip.log

'dict' object has no attribute 'iteritems'

Installed version 0.7.2 in a Python 3.5 environment. On running, received error

Django Version: 1.8.4
Exception Type: AttributeError
Exception Value:

'dict' object has no attribute 'iteritems'

Exception Location: .../lib/python3.5/site-packages/phonenumber_field/widgets.py in init, line 21

Solution was to replace
...
or prefix, values in _COUNTRY_CODE_TO_REGION_CODE.iteritems():
...

with
...
or prefix, values in _COUNTRY_CODE_TO_REGION_CODE.items():
...

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.