Django Phone Number Field

8.4.0 · active · verified Thu Apr 09

django-phonenumber-field is a Django library that integrates Google's `libphonenumber` (via `python-phonenumbers`) to provide an international phone number field for Django models and forms. It handles validation, formatting, and conversion of phone numbers according to international standards. The current version is 8.4.0, and the library maintains an active release cadence with multiple minor/patch releases throughout the year.

Warnings

Install

Imports

Quickstart

To quickly use `django-phonenumber-field`, first add `phonenumber_field` to your `INSTALLED_APPS` in `settings.py`. Then define a `PhoneNumberField` in your Django model. For national number formats and proper validation, it's recommended to set `PHONENUMBER_DEFAULT_REGION` in your settings. The field automatically handles `PhoneNumber` objects, providing methods for various formats like E.164, national, and international.

import os
import django
from django.conf import settings
from django.db import models
from phonenumber_field.modelfields import PhoneNumberField

settings.configure(
    INSTALLED_APPS=['phonenumber_field'],
    DATABASES={'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}},
    PHONENUMBER_DEFAULT_REGION='US' # Crucial for national formats
)
django.setup()

class Contact(models.Model):
    name = models.CharField(max_length=100)
    phone_number = PhoneNumberField(blank=True)

    def __str__(self):
        return f"{self.name}: {self.phone_number}"

# Example Usage:
# from django.core.management import call_command
# call_command('makemigrations', 'myapp') # if using in a real app
# call_command('migrate') # if using in a real app

contact1 = Contact.objects.create(name="Alice", phone_number="+12025550123")
contact2 = Contact.objects.create(name="Bob", phone_number="6502530000") # Assumes PHONENUMBER_DEFAULT_REGION='US'

print(contact1)
print(contact2)
print(contact1.phone_number.as_e164)
print(contact2.phone_number.as_national)

# Example with an invalid number (will raise ValidationError in a real form/model save)
# try:
#     Contact.objects.create(name="Invalid", phone_number="123")
# except Exception as e:
#     print(f"Caught expected error: {e}")

view raw JSON →