AUTH_USER_MODEL指的是尚未安装的模型“accounts.User”。

8
我正在使用定制的用户模型,该模型是通过扩展AbstractUser实现的。这是我的models.py文件:
    # -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models
from django.contrib.auth.models import AbstractUser
from django.contrib.auth.forms import UserCreationForm

from django import forms

# Create your models here.
class User(AbstractUser):
    pass

class SignUpForm(UserCreationForm):
    first_name = forms.CharField(max_length=30, required=False, help_text='Optional.')
    last_name = forms.CharField(max_length=30, required=False, help_text='Optional.')
    email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.')

    class Meta:
        model = User
        fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', )
enter code here

因此,当我尝试运行开发服务器或迁移数据库时,它返回以下错误:

Traceback (most recent call last):
  File "./manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
    utility.execute()
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute
    django.setup()
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/__init__.py", line 27, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
    app_config.import_models()
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models
    self.models_module = import_module(models_module_name)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/Users/shivbhatia/Desktop/WishList/accounts/models.py", line 6, in <module>
    from django.contrib.auth.forms import UserCreationForm
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/contrib/auth/forms.py", line 22, in <module>
    UserModel = get_user_model()
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/contrib/auth/__init__.py", line 198, 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 'accounts.User' that has not been installed

以下是我的settings.py文件:

"""
Django settings for WishList project.

Generated by 'django-admin startproject' using Django 1.11.5.

For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = secret key goes here

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'accounts',
    'lists',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'WishList.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'WishList.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

AUTH_USER_MODEL = 'accounts.User'


# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Asia/Kolkata'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

STATIC_URL = '/static/'

LOGIN_REDIRECT_URL = '/lists/'
LOGOUT_REDIRECT_URL = '/lists/'

我是新手Django开发者,对用户身份验证系统感到困惑。
因为我的用户必须具有friends字段,所以我必须使用自定义用户扩展功能。但是,我一直遇到这些问题。我已经在settings.py中安装了我的账户应用程序,但我感觉我错过了一些步骤。为什么它不能正常工作?
5个回答

8
我猜测问题出在依赖性上。你在accounts.models文件的顶部导入UserCreationForm,它又试图获取用户模型 - 但是该models文件的其余部分尚未被处理,因此User未定义。
你可以通过遵循推荐做法,将表单的导入和定义移到单独的forms.py文件中来轻松解决这个问题。

哇,那个完美地运行了!非常感谢!我有点困惑,为什么导入UserCreationForm会尝试获取用户模型? - Shiv Bhatia
因为ModelForm需要定义它所基于的模型; get_user_model()在auth forms.py模块的顶层运行。 - Daniel Roseman
谢谢。有些人说要把它放在模型、表单和视图中,但我需要把它放在表单中 =) - Kermit

2

当我尝试在models.py的顶部编写以下代码获取授权用户时,遇到了相同的错误:

User = get_user_model()

from django.db import models
from django.contrib.auth.models import AbstractUser
from django.contrib.auth import get_user_model

User = get_user_model()

class User(AbstractUser):
    is_official = models.BooleanField('official status', default=False)
    is_distro = models.BooleanField('distro status', default=False)
    is_subscriber = models.BooleanField('subscriber status', default=False)

我通过将User = get_user_model()移到User模型定义下方来解决了这个问题,这是有道理的,因为在User模型定义顶部调用get_user_model()意味着它正在引用一个尚不存在的模型。以下是有效的代码布局:

from django.db import models
from django.contrib.auth.models import AbstractUser
from django.contrib.auth import get_user_model

class User(AbstractUser):
    is_official = models.BooleanField('official status', default=False)
    is_distro = models.BooleanField('distro status', default=False)
    is_subscriber = models.BooleanField('subscriber status', default=False)

    def __str__(self):
        return self.username

User = get_user_model()

你可能没有这个确切的布局,但我猜主要观点是在同一文件中不要在定义模型之前引用模型,这就是为什么导入语句放在顶部


1

当我尝试将应用程序在INSTALLED_APPS中的位置移动时,它对我起作用了。


1
为了更好地理解这个问题,我将说明我如何解决它。对我而言,将其中一个导入语句(内部使用了User模型)从文件顶部移动,并将其放在定义User模型之后,可以解决这个问题。
from django.contrib.auth.models import AbstractUser, BaseUserManager
from django.db import models
from django.db.models.signals import post_save
from rest_framework.authtoken.models import Token
from .utils import generate_token, send_email, generate_id



class User(AbstractUser):
    """User model."""

    username   = None
    email      = models.EmailField(_('email address'), unique=True)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    objects = UserManager()

#### Moved the import statement here so that the issue is solved.
#### This function internally used User model which is only defined right above this.
from meter.tasks import apigeePipeline

def post_save_user_receiver(sender, instance, created, *args, **kwargs):
    if created:
        print("***********USer created**********")
        token = Token.objects.create(user=instance)
        send_email(instance.email, token.key)
        apigeePipeline(instance)


post_save.connect(post_save_user_receiver, sender=User)

-1

这是一个重要的问题: 尝试改变导入的顺序: 先尝试: from django.contrib.auth.models import AbstractUser 然后: from django.db import models


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接