Изменение имени пользователя модели User для использования PhoneNumberField вместо CharField вызывает ошибки - PullRequest
2 голосов
/ 06 ноября 2019

Я работаю над проектом, запущенным с cookiecutter-django, и я изменил имя пользователя модели User, чтобы использовать PhoneNumberField из пакета django-phonenumber-field вместо обычного 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 Ответ

1 голос
/ 06 ноября 2019

Я полагал, что решение для первой ошибки было о ChangeForm и CreationForm в forms.py приложения users в cookiecutter-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 создает экземпляр AnonymousUser, когда я выдаю manage.py migrate, который имеетневерное имя пользователя в соответствии с PhoneNumberField проверкой имени пользователя.

Решение, поскольку мы больше не зависим от django-guardian, просто его удаляли.

...