Django自定义认证后端报app_label相关错误排查与解决
Django配置自定义AUTHENTICATION_BACKENDS触发RuntimeError
配置自定义认证后端时触发如下报错:
Model class tainfo.apps.users.models.User doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.
问题场景
编写了支持手机号、用户名双登录的自定义认证后端,代码如下:
from django.contrib.auth.backends import ModelBackend import re from tainfo.apps.users.models import User def get_user_by_account(account): try: if re.match(r'1[3-9]\d{9}',account): user = User.objects.get(mobile=account) else: user = User.objects.get(username=account) return user except User.DoesNotExist: return None class UsernameMobileAuthBackend(ModelBackend): def authenticate(self,request,username=None,password=None,**kwargs): user = get_user_by_account(username) if user and user.check_password(password) and user.is_active: return user
在devsettings.py中添加配置AUTHENTICATION_BACKENDS = ['users.utils.UsernameMobileAuthBackend',]后就会触发上述报错,删除该配置则报错消失,但自定义认证后端的能力也无法生效。
已确认正常的配置项
- 自定义User模型正确继承AbstractUser,模型代码如下:
from django.contrib.auth.models import AbstractUser from django.db import models # Create your models here. class User(AbstractUser): mobile = models.CharField(max_length=11, unique=True, verbose_name='mobile',blank=True) email_active = models.BooleanField(default=False, verbose_name='emailisactive') class Meta: db_table = 'tb_users' verbose_name = 'user' verbose_name_plural = verbose_name def __str__(self): return self.username
- 配置文件基础配置无遗漏:已在
INSTALLED_APPS中注册users等应用,已通过AUTH_USER_MODEL指定自定义用户模型,相关配置如下:
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users.apps.UsersConfig', 'contents.apps.ContentsConfig', 'verifications.apps.VerificationsConfig', ] AUTH_USER_MODEL = 'users.User' AUTHENTICATION_BACKENDS = ['users.utils.UsernameMobileAuthBackend',]
解决方案
报错根因是自定义认证后端中User模型的导入路径错误:项目已将apps目录加入sys.path,导入User模型应使用from users.models import User,而非带全项目层级前缀的from tainfo.apps.users.models import User。修改导入路径后问题即可彻底解决。
内容的提问来源于stack exchange,提问作者Eric YJ Chung
相关产品推荐
相关产品推荐

