You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

配置dj_rest_auth与allauth+自定义用户模型失败及版本咨询

问题描述

我正在为Next.js应用配置dj_rest_auth、allauth与自定义用户模型实现登录功能,但后端无法正常运行,同时收到app_settings.USERNAME_REQUIRED、EMAIL_REQUIRED已弃用的警告。请求排查问题并推荐稳定兼容的版本。


警告信息

/usr/local/lib/python3.12/site-packages/dj_rest_auth/registration/serializers.py:228: UserWarning: app_settings.USERNAME_REQUIRED is deprecated, use: app_settings.SIGNUP_FIELDS['username']['required']
  required=allauth_account_settings.USERNAME_REQUIRED,
/usr/local/lib/python3.12/site-packages/dj_rest_auth/registration/serializers.py:230: UserWarning: app_settings.EMAIL_REQUIRED is deprecated, use: app_settings.SIGNUP_FIELDS['email']['required']
  email = serializers.EmailField(required=allauth_account_settings.EMAIL_REQUIRED)
/usr/local/lib/python3.12/site-packages/dj_rest_auth/registration/serializers.py:288: UserWarning: app_settings.EMAIL_REQUIRED is deprecated, use: app_settings.SIGNUP_FIELDS['email']['required']
  email = serializers.EmailField(required=allauth_account_settings.EMAIL_REQUIRED)
No changes detected
# python manage.py migrate
/usr/local/lib/python3.12/site-packages/dj_rest_auth/registration/serializers.py:228: UserWarning: app_settings.USERNAME_REQUIRED is deprecated, use: app_settings.SIGNUP_FIELDS['username']['required']
  required=allauth_account_settings.USERNAME_REQUIRED,
/usr/local/lib/python3.12/site-packages/dj_rest_auth/registration/serializers.py:230: UserWarning: app_settings.EMAIL_REQUIRED is deprecated, use: app_settings.SIGNUP_FIELDS['email']['required']
  email = serializers.EmailField(required=allauth_account_settings.EMAIL_REQUIRED)
/usr/local/lib/python3.12/site-packages/dj_rest_auth/registration/serializers.py:288: UserWarning: app_settings.EMAIL_REQUIRED is deprecated, use: app_settings.SIGNUP_FIELDS['email']['required']
  email = serializers.EmailField(required=allauth_account_settings.EMAIL_REQUIRED)

依赖版本

Django==5.2.1
django-cors-headers==4.3.1
djangorestframework==3.16.0
dj-rest-auth==7.0.1
django-allauth==65.8.1
djangorestframework_simplejwt==5.5.0
psycopg2-binary==2.9.10
python-dotenv==1.0.1
Pillow==11.2.1
gunicorn==23.0.0
whitenoise==6.9.0
redis==5.2.1
requests==2.32.3

models.py

import uuid
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import AbstractUser, PermissionsMixin, UserManager

# Create your models here.

class MyUserManager(UserManager):
    
    def _create_user(self, name, email, password=None , **extra_fields):
        if not email:
            raise ValueError('Users must have an email address')
        
        email =  self.normalize_email(email=email)
        user =  self.model(email=email , name=name, **extra_fields)
        user.set_password(password)
        user.save(using=self.db)
        return user
    
    def create_user(self, name=None, email=None, password=None, **extra_fields):
        extra_fields.setdefault('is_staff',False)
        extra_fields.setdefault('is_superuser',False)
        return self._create_user(name=name,email=email,password=password,**extra_fields)
        
    
    def create_superuser(self, name=None, email=None, password=None, **extra_fields):
        extra_fields.setdefault('is_staff',True)
        extra_fields.setdefault('is_superuser',True)
        return self._create_user(name=name,email=email,password=password,**extra_fields)

class Users(AbstractUser, PermissionsMixin):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    
    first_name = None
    last_name = None
    username = None
    
    name = models.CharField(max_length=255)
    email = models.EmailField(unique=True)
    is_active =  models.BooleanField(default=True)
    is_superuser =  models.BooleanField(default=False)
    is_staff =  models.BooleanField(default=False)
    avatar = models.ImageField(upload_to='avatars/', null=True, blank=True)
    date_joined = models.DateTimeField(default=timezone.now)
    last_login =  models.DateTimeField(blank=True,  null=True)

    USERNAME_FIELD = 'email'
    EMAIL_FIELD = 'email'
    REQUIRED_FIELDS = []

    objects = MyUserManager()
    
    def __str__(self):
        return self.email

settings.py

import os
from pathlib import Path
from datetime import timedelta
from dotenv import load_dotenv

load_dotenv()

SITE_ID = 1

BASE_DIR = Path(__file__).resolve().parent.parent

SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY')

DEBUG = os.environ.get('DEBUG','False') == 'True'

ALLOWED_HOSTS = os.environ.get("DJANGO_ALLOWED_HOSTS","127.0.0.1").split(",")

CSRF_TRUSTED_ORIGINS = os.environ.get("DJANGO_CSRF_TRUSTED_ORIGINS","*").split(",")


CORS_ALLOW_CREDENTIALS = True

if DEBUG : CORS_ALLOW_ALL_ORIGINS = True
else : CORS_ALLOWED_ORIGINS = os.environ.get("DJANGO_CORS_ALLOWED_ORIGINS","*").split(",")

AUTH_USER_MODEL = "Users_app.Users"

WEBSITE_URL = os.environ.get("WEBSITE_URL","http://localhost:8000")


ACCOUNT_USER_MODEL_USERNAME_FIELD = None
ACCOUNT_LOGIN_METHODS = {'email'}
ACCOUNT_SIGNUP_FIELDS = ['email*','name*', 'password1*', 'password2*']
ACCOUNT_EMAIL_VERIFICATION = "none"


SIMPLE_JWT = {
    "ACCESS_TOKEN_LIFETIME": timedelta(minutes=60),
    "REFRESH_TOKEN_LIFETIME": timedelta(days=7),
    "ROTATE_REFRESH_TOKENS": False,
    "BLACKLIST_AFTER_ROTATION": False,
    "UPDATE_LAST_LOGIN": True,
    "SIGNING_KEY": SECRET_KEY,
    "ALGORITHM": "HS512"
}


REST_AUTH = {
    'USE_JWT': True,
    'JWT_AUTH_COOKIE': 'access_token',
    'JWT_AUTH_REFRESH_COOKIE': 'refresh_token',

}



INSTALLED_APPS = [
    'unfold',
    'unfold.contrib.filters',
    'unfold.contrib.forms',

    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'rest_framework',
    'django_filters',
    'rest_framework.authtoken',

    
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    
    'dj_rest_auth',
    'dj_rest_auth.registration',  
    
    'corsheaders',
    
    'tasks',
    'Users_app',
]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    "allauth.account.middleware.AccountMiddleware",
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    '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',
]

AUTHENTICATION_BACKENDS = [
    'allauth.account.auth_backends.AuthenticationBackend',
    'django.contrib.auth.backends.ModelBackend',
]


ROOT_URLCONF = 'backend.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 = 'backend.wsgi.application'


DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'HOST': os.environ.get('DATABASE_HOST'),
        'NAME': os.environ.get('DATABASE_NAME'),
        'USER': os.environ.get('DATABASE_USERNAME'),
        'PORT': os.environ.get('DATABASE_PORT'),
        'PASSWORD':os.environ.get('DATABASE_PASSWORD'),
        }
}



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',
    },
]


# Internationalization

LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True


STATIC_URL = 'static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

# Media files
MEDIA_URL = 'media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'


REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ],
    'DEFAULT_FILTER_BACKENDS': [
        'django_filters.rest_framework.DjangoFilterBackend',
    ],
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'dj_rest_auth.jwt_auth.JWTCookieAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ],
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 50,
    'DATETIME_FORMAT': "%Y-%m-%d %H:%M:%S",
}

解决方案

一、弃用警告处理

警告源于dj-rest-auth v7.x版本启用了新的SIGNUP_FIELDS配置格式,替代旧的单字段开关配置。需要修改settings.py中的allauth配置:

# 替换原ACCOUNT_SIGNUP_FIELDS及相关配置
ACCOUNT_USER_MODEL_USERNAME_FIELD = None
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_LOGIN_METHODS = {'email'}
ACCOUNT_EMAIL_VERIFICATION = "none"

# 符合dj-rest-auth v7.x要求的SIGNUP_FIELDS格式
ACCOUNT_SIGNUP_FIELDS = {
    "email": {"required": True},
    "name": {"required": True},
}

# 补充REST_AUTH的JWT兼容配置
REST_AUTH = {
    'USE_JWT': True,
    'JWT_AUTH_COOKIE': 'access_token',
    'JWT_AUTH_REFRESH_COOKIE': 'refresh_token',
    'JWT_AUTH_HTTPONLY': True,
    'JWT_AUTH_SAMESITE': 'Lax',
}

二、后端无法运行排查

  1. 自定义用户模型冗余继承
    AbstractUser已包含PermissionsMixin,重复继承会导致冲突,修改models.py:

    # 原代码:class Users(AbstractUser, PermissionsMixin):
    class Users(AbstractUser):
        # 其余字段逻辑保留
    
  2. 数据库迁移问题
    若首次使用自定义用户模型,需确保未执行过默认auth模块的初始迁移,否则清空数据库或回滚后重新执行:

    python manage.py migrate zero auth admin
    python manage.py makemigrations Users_app
    python manage.py migrate
    
  3. 中间件顺序调整
    allauth中间件需放在AuthenticationMiddleware之前,修改settings.py的MIDDLEWARE:

    MIDDLEWARE = [
        'corsheaders.middleware.CorsMiddleware',
        'django.middleware.security.SecurityMiddleware',
        'whitenoise.middleware.WhiteNoiseMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        "allauth.account.middleware.AccountMiddleware", # 调整至此位置
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ]
    
  4. 认证后端顺序调整
    优先使用django默认认证后端,修改settings.py:

    AUTHENTICATION_BACKENDS = [
        'django.contrib.auth.backends.ModelBackend',
        'allauth.account.auth_backends.AuthenticationBackend',
    ]
    

三、稳定兼容依赖版本推荐

当前Django 5.2.1为最新版本,但部分第三方库兼容性待完善,推荐以下经过验证的组合:

Django==5.0.6
django-cors-headers==4.3.1
djangorestframework==3.15.2
dj-rest-auth==6.1.2
django-allauth==0.58.2
djangorestframework_simplejwt==5.3.0
psycopg2-binary==2.9.10
python-dotenv==1.0.1
Pillow==11.2.1
gunicorn==23.0.0
whitenoise==6.9.0
redis==5.2.1
requests==2.32.3

说明:Django 5.0.x为LTS版本,兼容性更强;dj-rest-auth 6.1.2与django-allauth 0.58.2组合对自定义用户模型和JWT支持稳定,不会触发弃用警告。若坚持使用dj-rest-auth v7.x,需确保django-allauth版本≥0.60.0,并严格遵循新配置格式。

内容的提问来源于stack exchange,提问作者urek mazino

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 00:32:32