在Django机型中存储电话号码的最佳方式是什么? [英] What's the best way to store Phone number in Django models

查看:780
本文介绍了在Django机型中存储电话号码的最佳方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在以模式存储电话号码

phone_number = models.CharField(max_length=12)

用户将输入一个电话号码,我会使用 SMS Authentication 的电话号码此应用程序将在全球使用。所以我也需要国家代码。是 CharField 是存储电话号码的好方法吗?而且,如何验证电话号码?

User would enter a phone number and I would use the phone number for SMS Authentication This application would be used globally. So I would also need country code. Is CharField is a good way to store phone number? And, how do I validate phone number?

提前感谢

推荐答案

标准格式 E.164 Twilio推荐的例子(谁有服务以及用于通过REST请求发送短信或电话呼叫的API)。

You might actually look into the internationally standardized format E.164, recommended by Twilio for example (who have a service and an API for sending SMS or phone-calls via REST requests).

这可能是存储电话号码的最普遍的方式,特别是如果您有国际电话号码。

This is likely to be the most universal way to store phone numbers, in particular if you have international numbers work with.

您的模型的一个注释:E.164号码的最大字符长度为15。

One note for your model: E.164 numbers have a max character length of 15.

要验证,您可以使用格式化,然后尝试请立即联系以验证。

To validate, you can employ some combination of formatting and then attempting to contact the number immediately to verify.

我相信在我的django项目中使用了以下内容:

I believe I used something like the following on my django project:

class ReceiverForm(forms.ModelForm):
    phone_number = forms.RegexField(regex=r'^\+?1?\d{9,15}$', 
                                error_message = ("Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed."))






编辑

看来,对一些人来说是有用的,似乎值得将下面的评论整合成一个更加完整的答案。根据 jpotter6 ,您也可以在模型上执行以下操作:

It appears that this post has been useful to some folks, and it seems worth it to integrate the comment below into a more full-fledged answer. As per jpotter6, you can do something like the following on your models as well:

models.py:

models.py:

from django.core.validators import RegexValidator

class PhoneModel(models.Model):
    ...
    phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.")
    phone_number = models.CharField(validators=[phone_regex], blank=True) # validators should be a list

这篇关于在Django机型中存储电话号码的最佳方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆