如何将电话号码字段添加到 django UserCreationForm?

Posted

技术标签:

【中文标题】如何将电话号码字段添加到 django UserCreationForm?【英文标题】:How do I add phone number field to django UserCreationForm? 【发布时间】:2020-12-10 22:07:27 【问题描述】:

我想添加 PhoneNumberField 以便在注册时使用用户的电话号码。我已经有 CreateUserForm 用来创建新用户的 UserCreationForm 模型。但是默认情况下它没有电话号码字段。我尝试通过在 forms.py 中添加 phone 变量来添加它,但它不起作用并给出以下错误。

forms.py

class CreateUserForm(UserCreationForm):
    phone=PhoneNumberField()
    class Meta:
        model = User
        fields = ['username', 'email', 'password1', 'password2', 'phone']

models.py

class CustomerReg(models.Model):
    user=models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE)
    name=models.CharField(max_length=200, null=True)
    email=models.EmailField(max_length=254)
    phone=PhoneNumberField(default=None)
def create_profile(sender, **kwargs):
    if kwargs['created']:
        user_profile=CustomerReg.objects.create(user=kwargs['instance'])

post_save.connect(create_profile, sender=User)

这是我在运行 python manage.py makemigrations 时遇到的错误

Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    main()
  File "manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "D:\djangoL2G\venvP\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line
    utility.execute()
  File "D:\djangoL2G\venvP\lib\site-packages\django\core\management\__init__.py", line 395, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "D:\djangoL2G\venvP\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv
    self.execute(*args, **cmd_options)
  File "D:\djangoL2G\venvP\lib\site-packages\django\core\management\base.py", line 368, in execute
    self.check()
  File "D:\djangoL2G\venvP\lib\site-packages\django\core\management\base.py", line 396, in check
    databases=databases,
  File "D:\djangoL2G\venvP\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks
    new_errors = check(app_configs=app_configs, databases=databases)
  File "D:\djangoL2G\venvP\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config
    return check_resolver(resolver)
  File "D:\djangoL2G\venvP\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver
    return check_method()
  File "D:\djangoL2G\venvP\lib\site-packages\django\urls\resolvers.py", line 408, in check
    for pattern in self.url_patterns:
  File "D:\djangoL2G\venvP\lib\site-packages\django\utils\functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "D:\djangoL2G\venvP\lib\site-packages\django\urls\resolvers.py", line 589, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "D:\djangoL2G\venvP\lib\site-packages\django\utils\functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "D:\djangoL2G\venvP\lib\site-packages\django\urls\resolvers.py", line 582, in urlconf_module
    return import_module(self.urlconf_name)
  File "C:\Python\Python36\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "D:\DjangoL2Gwiz\l2gproject\l2gProject\urls.py", line 23, in <module>
    path('',include('customer.urls')),
  File "D:\djangoL2G\venvP\lib\site-packages\django\urls\conf.py", line 34, in include
    urlconf_module = import_module(urlconf_module)
  File "C:\Python\Python36\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "D:\DjangoL2Gwiz\l2gproject\customer\urls.py", line 2, in <module>
    from . import views
  File "D:\DjangoL2Gwiz\l2gproject\customer\views.py", line 6, in <module>
    from .forms import CreateUserForm
  File "D:\DjangoL2Gwiz\l2gproject\customer\forms.py", line 35, in <module>
    class CreateUserForm(UserCreationForm):
  File "D:\djangoL2G\venvP\lib\site-packages\django\forms\models.py", line 268, in __new__
    raise FieldError(message)
django.core.exceptions.FieldError: Unknown field(s) (phone) specified for User

那么如何在我的表单中添加电话号码字段?

【问题讨论】:

这会帮助您回答您的问题吗? [***.com/questions/19130942/… 成功了。谢谢! 【参考方案1】:

我建议这样做:

from django.core.validators import RegexValidator

class CreateUserForm(UserCreationForm):
   phone_regex = RegexValidator(regex=r'^\+?1?\d9,15$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.")
   phone = forms.CharField(validators=[phone_regex], max_length=17)
   class Meta:
      model = User
      fields = ['username', 'email', 'password1', 'password2', 'phone']

【讨论】:

以上是关于如何将电话号码字段添加到 django UserCreationForm?的主要内容,如果未能解决你的问题,请参考以下文章

如何将计算字段添加到 Django 模型

如何在单个请求中使用 django 信号将数据保存在(用户和配置文件)表中?

如何将类添加到 Django 表单中的字段标记

如何将标签添加到Django管理员字段

Django Allauth - 如何将自定义 CSS 类添加到字段?

如何将引导类添加到模板中的 Django CreateView 表单字段?