您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

格式化django中的电话号码

5b51 2022/1/14 8:22:30 python 字数 2220 阅读 519 来源 www.jb51.cc/python

我的问题更容易用一个例子来解释: 我有一个电话号码存储在我的数据库中作为一串数字.让我们认为该领域被称为电话,它位于一个名为Business的模型中. 因此,要在模板中打印电话号码,在视图中创建business var之后,我将使用: {{ business.phone }} 这将显示数字字符串,如2125476321 打印这个电话号码的最佳方法是什么,如(212)547-6321?我可以在模型中

概述

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

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

{{ business.phone }}

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

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

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时,请将其写入模型中(但是无法将参数传递给函数)

总结

以上是编程之家为你收集整理的格式化django中的电话号码全部内容,希望文章能够帮你解决格式化django中的电话号码所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶