Я пытаюсь создать пользовательскую модель пользователя (как я это делал несколько раз ранее), пытаясь удалить поле «username» и заменить его полем «email».
Iсоздал новый проект и установил последнюю версию всех пакетов в venv:
Django==2.1.4
django-filter==2.0.0
djangorestframework==3.9.0
Markdown==3.0.1
pkg-resources==0.0.0
pytz==2018.7
Затем я создал проект со следующим макетом:
.
├── api
│ ├── admin.py
│ ├── apps.py
│ ├── __init__.py
│ ├── migrations
│ │ └── __init__.py
│ ├── models.py
│ ├── tests.py
│ └── views.py
├── manage.py
└── penguin_backend
├── __init__.py
├── settings.py
├── urls.py
└── wsgi.py
Затем я добавил следующеекод файла api/models.py
, который заменяет модель пользователя по умолчанию и класс менеджера пользователей:
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
from django.contrib.auth.models import PermissionsMixin
from django.core.mail import send_mail
from django.db import models
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
class UserManager(BaseUserManager):
use_in_migrations = True
def _create_user(self, email, password, **extra_fields):
"""
Create and save a user with the given username, email, and password.
"""
if not email:
raise ValueError('The given email must be set')
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email=None, password=None, **extra_fields):
extra_fields.setdefault('is_staff', False)
extra_fields.setdefault('is_superuser', False)
return self._create_user(email, password, **extra_fields)
def create_superuser(self, email, password, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
if extra_fields.get('is_staff') is not True:
raise ValueError('Superuser must have is_staff=True.')
if extra_fields.get('is_superuser') is not True:
raise ValueError('Superuser must have is_superuser=True.')
return self._create_user(email, password, **extra_fields)
class User(AbstractBaseUser, PermissionsMixin):
"""
An abstract base class implementing a fully featured User model with
admin-compliant permissions.
Username and password are required. Other fields are optional.
"""
first_name = models.CharField(_('first name'), max_length=30, blank=True)
last_name = models.CharField(_('last name'), max_length=150, blank=True)
email = models.EmailField(_('email address'), blank=True)
is_staff = models.BooleanField(
_('staff status'),
default=False,
help_text=_('Designates whether the user can log into this admin site.'),
)
is_active = models.BooleanField(
_('active'),
default=True,
help_text=_(
'Designates whether this user should be treated as active. '
'Unselect this instead of deleting accounts.'
),
)
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
objects = UserManager()
EMAIL_FIELD = 'email'
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['email']
class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')
abstract = True
def clean(self):
super().clean()
self.email = self.__class__.objects.normalize_email(self.email)
def get_full_name(self):
"""
Return the first_name plus the last_name, with a space in between.
"""
full_name = '%s %s' % (self.first_name, self.last_name)
return full_name.strip()
def get_short_name(self):
"""Return the short name for the user."""
return self.first_name
def email_user(self, subject, message, from_email=None, **kwargs):
"""Send an email to this user."""
send_mail(subject, message, from_email, [self.email], **kwargs)
Затем я добавил следующие две строки в penguin_backend/settings.py
, чтобы применить изменения:
INSTALLED_APPS = [
[...]
'api' # new
]
[...]
AUTH_USER_MODEL = 'api.User' # new
И это все.Однако при попытке выполнить какие-либо команды ./manage.py
я получаю следующую ошибку:
$ ./manage.py
Traceback (most recent call last):
File "/home/ksoviero/PycharmProjects/penguin_backend/venv/lib/python3.5/site-packages/django/apps/config.py", line 165, in get_model
return self.models[model_name.lower()]
KeyError: 'user'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/ksoviero/PycharmProjects/penguin_backend/venv/lib/python3.5/site-packages/django/contrib/auth/__init__.py", line 165, in get_user_model
return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False)
File "/home/ksoviero/PycharmProjects/penguin_backend/venv/lib/python3.5/site-packages/django/apps/registry.py", line 207, in get_model
return app_config.get_model(model_name, require_ready=require_ready)
File "/home/ksoviero/PycharmProjects/penguin_backend/venv/lib/python3.5/site-packages/django/apps/config.py", line 168, in get_model
"App '%s' doesn't have a '%s' model." % (self.label, model_name))
LookupError: App 'api' doesn't have a 'User' model.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "./manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "/home/ksoviero/PycharmProjects/penguin_backend/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/home/ksoviero/PycharmProjects/penguin_backend/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 357, in execute
django.setup()
File "/home/ksoviero/PycharmProjects/penguin_backend/venv/lib/python3.5/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/ksoviero/PycharmProjects/penguin_backend/venv/lib/python3.5/site-packages/django/apps/registry.py", line 120, in populate
app_config.ready()
File "/home/ksoviero/PycharmProjects/penguin_backend/venv/lib/python3.5/site-packages/django/contrib/admin/apps.py", line 24, in ready
self.module.autodiscover()
File "/home/ksoviero/PycharmProjects/penguin_backend/venv/lib/python3.5/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover
autodiscover_modules('admin', register_to=site)
File "/home/ksoviero/PycharmProjects/penguin_backend/venv/lib/python3.5/site-packages/django/utils/module_loading.py", line 47, in autodiscover_modules
import_module('%s.%s' % (app_config.name, module_to_search))
File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 665, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "/home/ksoviero/PycharmProjects/penguin_backend/venv/lib/python3.5/site-packages/django/contrib/auth/admin.py", line 6, in <module>
from django.contrib.auth.forms import (
File "/home/ksoviero/PycharmProjects/penguin_backend/venv/lib/python3.5/site-packages/django/contrib/auth/forms.py", line 20, in <module>
UserModel = get_user_model()
File "/home/ksoviero/PycharmProjects/penguin_backend/venv/lib/python3.5/site-packages/django/contrib/auth/__init__.py", line 170, in get_user_model
"AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'api.User' that has not been installed
И я понятия не имею, почему это происходит, когда это никогда не делалось раньше.Кто-нибудь видел это раньше?Есть идеи?
Спасибо!