Gitlab will migrate to a new storage backend starting 0300 UTC on 2020-04-04. We do not anticipate a maintenance window for this migration. Performance may be impacted over the weekend. Thanks for your patience.

Commit d0342e36 authored by Tanner Prestegard's avatar Tanner Prestegard Committed by GraceDB

Enhancements and bugfix for PhoneNumberField

parent 11f5bcfa
import phonenumbers
from django.db import models
from .validators import validate_phone
PHONE_NUMBER_FORMATS = ['E164', 'NATIONAL', 'INTERNATIONAL', 'RFC3966']
class PhoneNumberField(models.CharField):
validators = [validate_phone]
def __init__(self, *args, **kwargs):
# Get format and check values
self.format = kwargs.pop('format', 'E164')
if self.format not in PHONE_NUMBER_FORMATS:
raise ValueError('Phone number format must be one of {fmt}'.format(
fmt=", ".join(PHONE_NUMBER_FORMATS)))
# super __init__
super(PhoneNumberField, self).__init__(*args, **kwargs)
def get_prep_value(self, value):
value = super(PhoneNumberField, self).get_prep_value(value)
# Handle blank values
if value is None or value == '':
return value
# Return phone number as a formatted string
phone = phonenumbers.parse(value, 'US')
return phonenumbers.format_number(phone,
getattr(phonenumbers.PhoneNumberFormat, self.format))
......@@ -13,7 +13,3 @@ def validate_phone(value):
# Validate phone number
if not phonenumbers.is_valid_number(phone):
raise ValidationError('Not a valid phone number: {0}'.format(value))
# Return phone number as a formatted string
return phonenumbers.format_number(phone,
phonenumbers.PhoneNumberFormat.E164)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment