django自定义用户表的问题

问题描述

makemigrations时候,找不到自定义用户表

环境

python3.6
django2.0

相关代码

gold_app.models

from django.db import models
from django.contrib.auth.models import (
    BaseUserManager, AbstractBaseUser,PermissionsMixin
)
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from django.core.mail import send_mail


class UserProfileManager(BaseUserManager):
    use_in_migrations = True

    def _create_user(self, username, email, password, **extra_fields):
        """
        Create and save a user with the given username, email, and password.
        """
        if not username:
            raise ValueError('The given username must be set')
        email = self.normalize_email(email)
        username = self.model.normalize_username(username)
        user = self.model(username=username, email=email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, username, email=None, password=None, **extra_fields):
        extra_fields.setdefault('is_staff', False)
        extra_fields.setdefault('is_superuser', False)
        return self._create_user(username, email, password, **extra_fields)

    def create_superuser(self, username, 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(username, email, password, **extra_fields)


class MyUser(AbstractBaseUser, PermissionsMixin):
    '''账号表'''
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
        null=True
    )
    password = models.CharField(_('password'), max_length=128,
                                help_text=mark_safe('''<a href='password/'>修改密码</a>'''))
    name = models.CharField(max_length=32)
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)
    objects = UserProfileManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['name']
    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)

    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):
        # The user is identified by their email address
        return self.email

    def get_short_name(self):
        # The user is identified by their email address
        return self.email

    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)

    def __str__(self):
        return self.email




# Create your models here.

settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'gold_app',
    'one'
]
AUTH_USER_MODEL = 'gold_app.MyUser'

报错

(venv) E:\python\Gold>python manage.py makemigrations
Traceback (most recent call last):
  File "E:\python\Gold\venv\lib\site-packages\django\apps\config.py", line 165, in get_model
    return self.models[model_name.lower()]
KeyError: 'myuser'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "E:\python\Gold\venv\lib\site-packages\django\contrib\auth\__init__.py", line 194, in get_user_model
    return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False)
  File "E:\python\Gold\venv\lib\site-packages\django\apps\registry.py", line 202, in get_model
    return app_config.get_model(model_name, require_ready=require_ready)
  File "E:\python\Gold\venv\lib\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 'gold_app' doesn't have a 'MyUser' 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 "E:\python\Gold\venv\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line
    utility.execute()
  File "E:\python\Gold\venv\lib\site-packages\django\core\management\__init__.py", line 347, in execute
    django.setup()
  File "E:\python\Gold\venv\lib\site-packages\django\__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "E:\python\Gold\venv\lib\site-packages\django\apps\registry.py", line 120, in populate
    app_config.ready()
  File "E:\python\Gold\venv\lib\site-packages\django\contrib\admin\apps.py", line 23, in ready
    self.module.autodiscover()
  File "E:\python\Gold\venv\lib\site-packages\django\contrib\admin\__init__.py", line 26, in autodiscover
    autodiscover_modules('admin', register_to=site)
  File "E:\python\Gold\venv\lib\site-packages\django\utils\module_loading.py", line 47, in autodiscover_modules
    import_module('%s.%s' % (app_config.name, module_to_search))
  File "C:\Users\Administrator\AppData\Local\Programs\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 "E:\python\Gold\venv\lib\site-packages\django\contrib\auth\admin.py", line 6, in <module>
    from django.contrib.auth.forms import (
  File "E:\python\Gold\venv\lib\site-packages\django\contrib\auth\forms.py", line 20, in <module>
    UserModel = get_user_model()
  File "E:\python\Gold\venv\lib\site-packages\django\contrib\auth\__init__.py", line 199, 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 'gold_app.MyUser' that has not been installed
阅读 4.1k
2 个回答
    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')
        **abstract = True**

需要 abstract = True,表示这是一个抽象模型,把这行注释掉再执行一次。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题