2 回答

TA貢獻(xiàn)1817條經(jīng)驗(yàn) 獲得超14個(gè)贊
Django不會(huì)自己格式化數(shù)字。但是,您可以構(gòu)建自己的函數(shù)來(lái)執(zhí)行此操作。考慮使用(鏈接)。在 models.py 中為此創(chuàng)建另一個(gè)函數(shù):python-phonenumbers
import phonenumbers
class Cards:
phone = models.CharField(max_length=12, null=True)
.....
def formatted_phone_number(self, country=None):
rtval = phonenumbers.parse(self.phone, country)
return rtval
然后在您的:template
{{ card.formatted_phone_number }}
注意:不能直接從模板傳遞參數(shù)。因此,該函數(shù)必須事先知道您將使用哪種國(guó)家/地區(qū)格式。

TA貢獻(xiàn)1812條經(jīng)驗(yàn) 獲得超5個(gè)贊
您可以編寫此幫助程序函數(shù):
def insert_str(string, str_to_insert, index):
return string[:index] + str_to_insert + string[index:]
,然后使用它來(lái)在需要時(shí)插入字符。如果括號(hào)的位置是固定的(每個(gè)電話號(hào)碼都相同,如您提供的示例所示),那么您可以簡(jiǎn)單地執(zhí)行以下操作:
phone = insert_str(phone, '(', 1)
phone = insert_str(phone, '(', 5) # there's already an extra '('
phone = insert_str(phone, ' ', 6)
phone = insert_str(phone, '-', 10)
添加回答
舉報(bào)