更改用户模型的用户名以使用PhoneNumberField而不是CharField会导致错误

时间:2019-11-06 13:25:17

标签: django cookiecutter-django

我正在从cookiecutter-django开始的项目中工作,我更改了User模型的用户名,以使用django-phonenumber-field包中的PhoneNumberField而不是普通的models.CharField,我尝试发出manage.py makemigrations时收到此错误:

Traceback (most recent call last):
  File "./manage.py", line 30, in <module>
    execute_from_command_line(sys.argv)
  File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute
    django.setup()
  File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/apps/registry.py", line 122, in populate
    app_config.ready()
  File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/contrib/admin/apps.py", line 24, in ready
    self.module.autodiscover()
  File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover
    autodiscover_modules('admin', register_to=site)
  File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/utils/module_loading.py", line 47, in autodiscover_modules
    import_module('%s.%s' % (app_config.name, module_to_search))
  File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/ahsh/Projects/xpay_stuff/communites_dj_backend/community_backend/users/admin.py", line 10, in <module>
    from community_backend.users.forms import UserChangeForm, UserCreationForm
  File "/home/ahsh/Projects/xpay_stuff/communites_dj_backend/community_backend/users/forms.py", line 8, in <module>
    class UserChangeForm(forms.UserChangeForm):
  File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/forms/models.py", line 256, in __new__
    apply_limit_choices_to=False,
  File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/forms/models.py", line 172, in fields_for_model
    formfield = f.formfield(**kwargs)
  File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/phonenumber_field/modelfields.py", line 106, in formfield
    return super().formfield(**defaults)
  File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 1093, in formfield
    return super().formfield(**defaults)
  File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 891, in formfield
    return form_class(**defaults)
  File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/forms/fields.py", line 214, in __init__
    super().__init__(**kwargs)
TypeError: __init__() got an unexpected keyword argument 'region'

解决了该错误(如下所述)后,我发出了运行正常的manage.py makemigrations,当我尝试发出manage.py migrate时又遇到了另一个错误:

Traceback (most recent call last):
  File "./manage.py", line 30, in <module>
    execute_from_command_line(sys.argv)
  File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute
    output = self.handle(*args, **options)
  File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/core/management/base.py", line 83, in wrapped
    res = handle_func(*args, **kwargs)
  File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 257, in handle
    self.verbosity, self.interactive, connection.alias, apps=post_migrate_apps, plan=plan,
  File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/core/management/sql.py", line 51, in emit_post_migrate_signal
    **kwargs
  File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/dispatch/dispatcher.py", line 175, in send
    for receiver in self._live_receivers(sender)
  File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/dispatch/dispatcher.py", line 175, in <listcomp>
    for receiver in self._live_receivers(sender)
  File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/guardian/management/__init__.py", line 33, in create_anonymous_user
    User.objects.get(**lookup)
  File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/db/models/query.py", line 399, in get
    clone = self.filter(*args, **kwargs)
  File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/db/models/query.py", line 892, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/db/models/query.py", line 910, in _filter_or_exclude
    clone.query.add_q(Q(*args, **kwargs))
  File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1290, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
  File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1318, in _add_q
    split_subq=split_subq, simple_col=simple_col,
  File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1251, in build_filter
    condition = self.build_lookup(lookups, col, value)
  File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1116, in build_lookup
    lookup = lookup_class(lhs, rhs)
  File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/db/models/lookups.py", line 20, in __init__
    self.rhs = self.get_prep_lookup()
  File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/db/models/lookups.py", line 70, in get_prep_lookup
    return self.lhs.output_field.get_prep_value(self.rhs)
  File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/phonenumber_field/modelfields.py", line 83, in get_prep_value
    raise ValueError("“%s” is not a valid phone number." % value.raw_input)
ValueError: “AnonymousUser” is not a valid phone number.

1 个答案:

答案 0 :(得分:2)

我发现第一个错误的解决方案是用户名字段ChangeForm中的CreationForm应用的forms.py中的userscookiecutter-django用户名使用默认字段类,因此我不得不更改该类以使用PhoneNumberField包中的表单字段。 这是代码:

class UserChangeForm(forms.UserChangeForm):
    class Meta(forms.UserChangeForm.Meta):
        model = User
        field_classes = {"username": PhoneNumberField}

class UserCreationForm(forms.UserCreationForm):

    error_message = forms.UserCreationForm.error_messages.update(
        {"duplicate_username": _("This username has already been taken.")})

    class Meta(forms.UserCreationForm.Meta):
        model = User
        field_classes = {"username": PhoneNumberField}

    def clean_username(self):
        username = self.cleaned_data["username"]

        try:
            User.objects.get(username=username)
        except User.DoesNotExist:
            return username

        raise ValidationError(self.error_messages["duplicate_username"])

仅添加了field_classes = {"username": PhoneNumberField}

对于第二个错误,我发现当我发布django-guardian时,manage.py migrate创建了AnonymousUser实例,根据PhoneNumberField用户名验证,该实例的用户名无效。

由于我们不再依赖django-guardian,因此解决方案就是删除它。