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.
pip install django-phonenumber-field[phonenumbers]Verified import paths — ran on the pinned version, not inferred.
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.
Replace `PhoneNumberInternationalFallbackWidget` with `RegionalPhoneNumberWidget` in your forms or widget definitions.
Refactor custom validation logic to align with Django's form field validation, moving checks to the form's `clean_FIELD()` or `clean()` methods. Update any `invalid_phone_number` error codes to `invalid`.
Test your application thoroughly after upgrading to 7.2.0 or later, especially if you rely on `values_list()` or raw database interactions with `PhoneNumberField` values.
Always set `PHONENUMBER_DEFAULT_REGION` (e.g., `PHONENUMBER_DEFAULT_REGION = 'US'`) in your Django `settings.py`.
You may need to apply custom CSS or use Django's template rendering features to manually position the `PhoneNumberPrefixWidget` and the national number input side-by-side.
Ensure that any string values assigned to `PhoneNumberField` instances include the country code (e.g., `'+12025550123'`) or explicitly parse it with a region if it's a national number, e.g., `PhoneNumber.from_string('6044011234', region='CA')`.Ensure the package is installed using `pip install django-phonenumber-field[phonenumbers]` (or `django-phonenumber-field[phonenumberslite]` for a lighter version), and `phonenumber_field` is added to `INSTALLED_APPS` in your Django `settings.py`.
Set `PHONENUMBER_DEFAULT_REGION = 'US'` (or your desired ISO 3166-1 two-letter country code) in your `settings.py` file to provide a default region for national number parsing, or ensure users always enter numbers with an international prefix (e.g., `+12125552368`).
The `PhoneNumberField` on a model returns a `PhoneNumber` object. Access the formatting properties on this object. For example, if `phone_number` is your field, use `my_instance.phone_number.as_international`.
Import `PhoneNumberField` from the correct location: `from phonenumber_field.formfields import PhoneNumberField` when defining forms, or `from phonenumber_field.modelfields import PhoneNumberField` when defining model fields.