加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

格式化django中的电话号码

发布时间:2020-12-16 23:10:21 所属栏目:Python 来源:网络整理
导读:我的问题更容易用一个例子来解释: 我有一个电话号码存储在我的数据库中作为一串数字.让我们认为该领域被称为电话,它位于一个名为Business的模型中. 因此,要在模板中打印电话号码,在视图中创建business var之后,我将使用: {{ business.phone }} 这将显示数
我的问题更容易用一个例子来解释:

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

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

{{ business.phone }}

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

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

解决方法

如果phonenumbers的格式没有改变,你可以编写自己的函数来格式化phonenumber(见 this).更好的方法是使用第三方库为您完成,例如 python-phonenumbers.最简单的方法是执行以下操作:
import phonenumbers
class Business(models.Model):
    phone = ...

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

在模板中

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

或者(或同时)write a custom template filter格式化语音.它看起来像:

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

并写道:

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读