Format phone number in django

My question is easier to explain with an example:

I have a phone number that is stored in my database as a string of numbers. Let's sit that the field is called the phone, and it is inside the model called "Business".

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

{{ business.phone }} 

This will display a string of numbers, e.g. 2125476321

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

+6
source share
1 answer

If the formatting of the phonograms does not change, you can write your own function for formatting the number of calls (see this ). A better approach would be to use a third-party library for this, like python-phonenumbers . The easiest way 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 at the same time) write a custom template filter to format the caller's number. It will look like this:

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

and it is written:

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

If you intend to use formatting in a template, write a template filter. If you think that you need formatting in other aspects of your application, for example, when listing names in the administrator, write it in the model (but lose the ability to pass parameters to the function)

+11
source

Source: https://habr.com/ru/post/908858/


All Articles