我正在尝试在自定义身份验证模型时自定义身份验证后端,但由于我使用的是get_user_model()
函数,因此一直遇到此错误。
django.core.exceptions.ImproperlyConfigured:AUTH_USER_MODEL指的是尚未安装的模型'base.User'
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'base.apps.BaseConfig',
'core.apps.AccountsConfig',
'system.apps.SystemConfig',
]
自定义后端:
class UserBackend(object):
def authenticate(self, request, username=None, password=None, **kwargs):
usermodel = User
try:
usr = usermodel.objects.get(username=username)
password_valid = usr.check_password(password)
if usr and password_valid:
return usr
raise PermissionDenied
except usermodel.DoesNotExist:
return PermissionDenied
return None
def get_user(self, user_id):
usermodel = User
try:
return usermodel.objects.get(pk=user_id)
except usermodel.DoesNotExist:
return None
设置:
AUTH_USER_MODEL = 'base.User'
AUTHENTICATION_BACKENDS = (
'base.models.UserBackend',
)
base.User
模型:
class User(AbstractUser):
fullname = models.CharField(max_length=35, null=True, blank=True)
picture = models.ManyToManyField('ImageFile', verbose_name="ProfilePicture", blank=True)
bio = models.CharField(max_length=255, null=True, blank=True)
link = models.URLField(null=True, blank=True, default="")
is_private = models.BooleanField(default=False)
is_official = models.BooleanField(default=False)
注意:UserBackend位于文件末尾,class User(AbstractUser)
位于文件末尾
答案 0 :(得分:1)
对我来说是一样的。我花了一个多小时才发现您的应用程序的models.py中没有CustomBackend(BaseBackend)和CustomUser(AbstractUser)。在官方Django文档中找不到此信息。
models.py:
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class User(AbstractUser):
last_name = models.CharField(max_length=50)
first_name = models.CharField(max_length=50)
auth.py(任意名称,位于“用户”应用中):
from django.db import models
from django.contrib.auth.backends import BaseBackend
class UserAuth(BaseBackend):
def authenticate(self, request, username, password):
pass
def get_user(self, user_id):
pass
settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'users.apps.UsersConfig'
]
AUTH_USER_MODEL = 'users.User'
AUTHENTICATION_BACKENDS = [
'users.auth.UserAuth'
]
答案 1 :(得分:0)
base.models
文件中有一个导入from django.contrib.auth.backends import ModelBackend
,即使我删除了自定义AUTHENTICATION_BACKENDS
,也导致了此错误。删除此导入后,尽管我将后端类从在base.models
应用中从backend
到base
文件(我认为这不是必需的,我只是为了获得更具可读性的代码而已)