Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting a phone number in django

My question is easier to explain with an example:

I have a phone number stored in my database as a string of numbers. Lets sat that the field is called phone, and it is inside a model called Business.

So, to print the phone number in a template, after creating the business var in the view I would use:

{{ business.phone }}

This will display the string of numbers like 2125476321

What is the best way to pretty print this phone number like (212) 547-6321? Is there any method that I can use inside the model?

like image 593
AlexBrand Avatar asked Feb 19 '12 23:02

AlexBrand


People also ask

Is there a phone number field in Django?

A Django library which interfaces with python-phonenumbers to validate, pretty print and convert phone numbers. python-phonenumbers is a port of Google's libphonenumber library, which powers Android's phone number handling. Included are: PhoneNumber, a pythonic wrapper around python-phonenumbers' PhoneNumber class.

What's the best way to store phone number in Django models?

You can use the phonenumber_field library. It is a port of Google's libphonenumber library, which powers Android's phone number handling.


1 Answers

If the formatting of the phonenumbers doesn't change you can write your own function to format the phonenumber (see this). A better approach would be to use a 3rd party library to do it for you, such as python-phonenumbers. The easiest approach is to do something like this:

import phonenumbers
class Business(models.Model):
    phone = ...

    def formatted_phone(self, country=None):
        return phonenumbers.parse(self.phone, country)

in the template

 # We can't pass parameters from the template so we have to hope that python-phonenumbers guesses correctly
 {{ business.formatted_phone }}

Alternatively (or concurrently) write a custom template filter to format the phonenumber. It would look like:

{{ business.phone|phonenumber }} or {{ business.phone|phonenumber:"GB" }} 

and written:

import phonenumbers
@register.filter(name='phonenumber')
def phonenumber(value, country=None):
   return phonenumbers.parse(value, country)

If you are only going to use the formatting in the template, write a template filter. If you think you will need the formatting in other aspects of your app, for example when listing the phonenumbers in the admin, write it in the model (but lose the ability to pass parameters to the function)

like image 62
Timmy O'Mahony Avatar answered Nov 09 '22 17:11

Timmy O'Mahony