【问题标题】:How to store a phone number in Django model?如何在 Django 模型中存储电话号码?
【发布时间】:2020-04-16 04:58:11
【问题描述】:

我想在我的模型中存储用户的电话号码,但不知道以哪种格式存储。

存储电话号码的最佳做法是什么?如何通过注册表单(以及通过序列化程序等)轻松处理它?我是 Django 新手,所以我需要一些关于此的建议。

【问题讨论】:

  • 我建议你使用一个库,比如django-phonenumber-field
  • 我确实做到了。但是,我遇到了许多错误,例如:无法将 int 转换为 PhoneNumber 等等。
  • 那么您是如何想出将int 存储为电话号码的?
  • 检查我的答案,切勿将电话号码存储为整数。它们也可以包含字母数字字符。作为原则,如果你不在数学方程上使用类似数字的东西,那应该是字符串而不是 int。

标签: django django-models


【解决方案1】:

您应该使用正则表达式验证器。您不需要 3rd 方库。

# models.py
from django.core.validators import RegexValidator

# this is your user model
class YourUser(AbstractUser):

    # error message when a wrong format entered
    phone_message = 'Phone number must be entered in the format: 05999999999' 

     # your desired format 
    phone_regex = RegexValidator(
        regex=r'^(05)\d{9}$',
        message=phone_message
    )

    # finally, your phone number field
    phone = models.CharField(validators=[phone_regex], max_length=60,
                             null=True, blank=True)

【讨论】:

  • 你能解释一下这是什么意思吗:r'^(05)\d{9}$'
  • 以“05”开头并以 {nine} (d)igits 继续
  • 你可以在这里查看备忘单rexegg.com/regex-quickstart.html
猜你喜欢
  • 1970-01-01
  • 2013-10-08
  • 2013-12-09
  • 1970-01-01
  • 2020-01-20
  • 2015-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多