[django] What's the best way to store Phone number in Django models

I am storing a phone number in model like this:

phone_number = models.CharField(max_length=12)

User would enter a phone number and I would use the phone number for SMS Authentication This application would be used globally. So I would also need country code. Is CharField a good way to store phone number? And, how do I validate the phone number?

This question is related to django django-forms django-validation

The answer is


Others mentioned django-phonenumber-field. To get the display format how you want you need to set PHONENUMBER_DEFAULT_FORMAT setting to "E164", "INTERNATIONAL", "NATIONAL", or "RFC3966", however you want it displayed. See the GitHub source.


This solution worked for me:

First install django-phone-field

command: pip install django-phone-field

then on models.py

from phone_field import PhoneField
...

class Client(models.Model):
    ...
    phone_number = PhoneField(blank=True, help_text='Contact phone number')

and on settings.py

INSTALLED_APPS = [...,
                  'phone_field'
]

It looks like this in the end

phone in form


Use django-phonenumber-field: https://github.com/stefanfoulis/django-phonenumber-field

pip install django-phonenumber-field

Validation is easy, text them a little code to type in. A CharField is a great way to store it. I wouldn't worry too much about canonicalizing phone numbers.


Use CharField for phone field in the model and the localflavor app for form validation:

https://docs.djangoproject.com/en/1.7/topics/localflavor/


I will describe what I use:

Validation: string contains more than 5 digits.

Cleaning: removing all non digits symbols, write in db only numbers. I'm lucky, because in my country (Russia) everybody has phone numbers with 10 digits. So I store in db only 10 diits. If you are writing multi-country application, then you should make a comprehensive validation.

Rendering: I write custom template tag to render it in template nicely. Or even render it like a picture - it is more safe to prevent sms spam.


It all depends in what you understand as phone number. Phone numbers are country specific. The localflavors packages for several countries contains their own "phone number field". So if you are ok being country specific you should take a look at localflavor package (class us.models.PhoneNumberField for US case, etc.)

Otherwise you could inspect the localflavors to get the maximun lenght for all countries. Localflavor also has forms fields you could use in conjunction with the country code to validate the phone number.