无法使用Django 2.1和Python 3.5创建自定义用户模型

时间:2018-12-04 22:22:57

标签: python django python-3.5 django-2.1

我正在尝试创建一个自定义用户模型(就像我之前做过的几次),以尝试删除“用户名”字段并将其替换为“电子邮件”字段。

我创建了一个全新的项目,并在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

而且我不知道为什么以前从未这样做过,为什么要这么做。有没有人见过这个?有什么想法吗?

谢谢!

1 个答案:

答案 0 :(得分:-1)

检查以下选项:

1-确保将api应用添加到django settings.py中的installed_apps中。

2-不要从django.contrib默认路径导入User模型。始终从您的api.models导入,或者始终使用User = get_user_model()

,以及为什么使用abstract=True。并非如此。

我真的建议阅读本文(How to extend djagno user model),并根据建议的方案,查看为django应用选择哪种计划。因为它始终是覆盖djagno User模型的最佳解决方案。