格式化django中的电话号码
发布时间:2021-02-20 11:12:57 所属栏目: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时,请将其写入模型中(但是无法将参数传递给函数) (编辑:4S站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
- python – 定义中的包装方法名称
- python – 什么是django.utils.functional .__ p
- python – 使用正则表达式查找所有出现的交替数字
- python – 从appengine应用程序上传文件到谷歌云
- Python使用urllib2模块实现断点续传下载的方法
- python – 如何在`scipy.integrate.dblquad`中增
- python – 带有postgres的游标,存储数据的位置以
- python – ‘AnonymousUser’对象没有属性’后端
- python – 浏览器和wget加载JPEG不同?
- python – 逐行文件处理,for-loop vs with
热点阅读