I'm using the Django 2.0, Python 3.7, and the Django PhoneNumber field -- https://github.com/stefanfoulis/django-phonenumber-field and have set up my model thusly ...
class Coop(models.Model):
name = models.CharField(max_length=250, null=False)
type = models.ForeignKey(CoopType, on_delete=None)
address = AddressField(on_delete=models.CASCADE)
enabled = models.BooleanField(default=True, null=False)
phone = PhoneNumberField(null=True)
email = models.EmailField(null=True)
web_site = models.TextField()
I have added this in my settings.py file ...
PHONENUMBER_DB_FORMAT="RFC3966"
However, when I submit my form using the following JSON ...
{
"name": "3999",
"type": {
"name": "Coworking Space"
},
"address": {
"street_number": "222",
"route": "1212",
"raw": "222 W. Merchandise Mart Plaza, Suite 1212",
"formatted": "222 W. Merchandise Mart Plaza, Suite 1212",
"latitude": 41.88802611,
"longitude": -87.63612199,
"locality": {
"name": "Chicago",
"postal_code": "60654",
"state": 1
}
},
"enabled": true,
"phone": "303-234-1234",
"email": null,
"web_site": "http://www.1871.com/"
}
I get this error (a 400 response) ...
{"phone":["The phone number entered is not valid."]}
How else can I configure my server to recognize my phone number format (or do I need to change the format)?
I see three ways of achieving this:
Option 1
Use a RegEx validator inside your PhoneNumberField
:
from django.core.validators import RegexValidator
...
phone = PhoneNumberField(null=True, validators=[RegexValidator(r'^\d{3}-\d{3}-\d{4}$')])
Option 2
According to documentation, you can set the format to be NATIONAL
and then set the region. As such, you can use in your settings:
PHONENUMBER_DB_FORMAT = 'NATIONAL'
PHONENUMBER_DEFAULT_REGION = 'US'
Option 3
Use a RegEx validator , but change your field to be a CharField
.
from django.core.validators import RegexValidator
...
phone = models.CharField(null=True, validators=[RegexValidator(r'^\d{3}-\d{3}-\d{4}$')])
As documentation says:
Recommended is one of the globally meaningful formats 'E164', 'INTERNATIONAL' or 'RFC3966'. 'NATIONAL' format require to set up PHONENUMBER_DEFAULT_REGION variabl
So you need to setup your default region. eg: PHONENUMBER_DEFAULT_REGION='US'
in your settings.py
.
Use the regular expression to allow hyphen in between. It will allow these formats * 123-456-7890 * 333-333-4444 * 1234567890 * 123456789 * 123-4567-890 * 14157059247
Regular expression ^\\d{3}-\\d{3}-\\d{4}$
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.