When storing phone numbers in Django, should I store them as an raw digits or use django.contrib.localflavor?
Asked Answered
P

3

6

The title may have been confusing, but please let me explain:

Currently when I am storing phone number with raw digits like 5554441234. Then in my template I was going to "format" the number into something like 555-444-1234.

I realized in Django's localflavor, there is a US phone number field that checks if a string is in XXX-XXX-XXXX format.

So my question is should I enter the phone number as raw digits then format it in the template or should I enter the phone number in the formatted way using localflavor?

If I choose the latter, would the XXX-XXX-XXXX format restriction apply even to the database API level or in the Django admin page?

Prayerful answered 30/3, 2012 at 10:6 Comment(0)
G
9

Store them as entered, only strip surrounding white space if necessary. The way a user formats its number stores semantic information that you do not want to lose by normalizing it. In the US the format XXX-XXX-XXXX is very common, but other locales use totally different formats. For example, where I live some common formats are: XX-XXX XXX XX, XXX/XXX XX XX, +46(0)70-XXX XX XX and so on ad nausem.

The number displayed to the user should be in the same format as entered, otherwise he or she will think of it as munged or may not even recognize the number if it is formatted in a different style than the user is used to. See also this discussion: http://discuss.fogcreek.com/dotnetquestions/default.asp?cmd=show&ixPost=6079&ixReplies=6

Gametocyte answered 30/3, 2012 at 10:34 Comment(2)
How would I check in the Django admin? Is there a way to tag the CharField to enforce the XXX-XXX-XXXX validation on a models.py level?Prayerful
The point is that you should not try to enforce it. It's not your site's business to tell users how they should format their own phone numbers.Gametocyte
T
2

If you're using forms framework (for example, in the Django admin), the validation of the input will be done on the application level. So, to enter phone number in the form, you have to format it to XXX-XXX-XXXX.

On the database level, it's just a CharField, so database doesn't do any checks for the format.

Tracee answered 30/3, 2012 at 10:33 Comment(1)
If you want to validate on models.py level, you can attach your function to pre_save signal for the model. In that function you can use localflavor for validate the input.Tracee
N
0

Try Django-phoneno. field . It is available on Python website. You need to install using pip install django-phonenumber-field

https://pypi.python.org/pypi/django-phonenumber-field/0.2a3

Nomination answered 17/5, 2014 at 15:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.