AlexBrand
AlexBrand

Reputation: 12429

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?

Upvotes: 7

Views: 10848

Answers (1)

Timmy O'Mahony
Timmy O'Mahony

Reputation: 53998

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)

Upvotes: 14

Related Questions