格式化django中的电话号码

Ale*_*and 6 django django-models

我的问题更容易用一个例子来解释:

我有一个电话号码存储在我的数据库中作为一串数字.让我们认为该领域被称为电话,它位于一个名为Business的模型中.

因此,要在模板中打印电话号码,在视图中创建business var之后,我将使用:

{{ business.phone }}
Run Code Online (Sandbox Code Playgroud)

这将显示数字字符串,如2125476321

打印这个电话号码的最佳方法是什么,如(212)547-6321?我可以在模型中使用任何方法吗?

Tim*_*ony 11

如果phonenumbers的格式没有改变,你可以编写自己的函数来格式化phonenumber(见这个).更好的方法是使用第三方库为您完成,例如python-phonenumbers.最简单的方法是做这样的事情:

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

    def formatted_phone(self, country=None):
        return phonenumbers.parse(self.phone, country)
Run Code Online (Sandbox Code Playgroud)

在模板中

 # We can't pass parameters from the template so we have to hope that python-phonenumbers guesses correctly
 {{ business.formatted_phone }}
Run Code Online (Sandbox Code Playgroud)

或者(或同时)编写自定义模板过滤器以格式化语音.它看起来像:

{{ business.phone|phonenumber }} or {{ business.phone|phonenumber:"GB" }} 
Run Code Online (Sandbox Code Playgroud)

并写道:

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

如果您只想在模板中使用格式,请编写模板过滤器.如果您认为在应用程序的其他方面需要格式化,例如在管理员中列出phonenumbers时,请将其写入模型中(但是无法将参数传递给函数)

  • 这实际上并没有为你编号,你更喜欢写一些类似的东西:return phonenumbers.format_number(phonenumbers.parse(value,country),phonenumbers.PhoneNumberFormat.NATIONAL) (7认同)