使用DRF、dj-rest-auth和django-allauth注册用户时遇AttributeError问题
问题:DRF + dj-rest-auth + django-allauth 用户注册填邮箱触发AttributeError
错误信息
AttributeError at /api/v1/dj-rest-auth/registration/ 'EmailAddressManager' object has no attribute 'is_verified'
现象描述
留空邮箱字段时可成功注册新用户,填写邮箱则触发上述错误。
相关配置
settings.py 模板与邮件配置
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / "templates"], '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', "django.template.context_processors.request", ], }, }, ] EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend" SITE_ID = 1
项目urls.py
urlpatterns = [ path('admin/', admin.site.urls), path('', include('apps.pages.front.urls')), path('api/v1/', include("apps.contacts.api.urls")), path('api-auth/', include("rest_framework.urls")), path("api/v1/dj-rest-auth/", include("dj_rest_auth.urls")), path("api/v1/dj-rest-auth/registration/", include("dj_rest_auth.registration.urls")), ]
INSTALLED_APPS
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'django.contrib.sites', "rest_framework", "corsheaders", "rest_framework.authtoken", "allauth", "allauth.account", "allauth.socialaccount", "dj_rest_auth", 'dj_rest_auth.registration', 'drf_spectacular', 'django_filters', 'apps.pages.apps.PagesConfig', 'apps.accounts.apps.AccountsConfig', 'apps.contacts.apps.ContactsConfig', ]
注:已创建自定义用户模型,应用放在专用apps文件夹中
解决办法
1. 校准自定义用户模型与allauth的配置
确保allauth能正确识别自定义用户模型的邮箱字段,在settings.py中添加或调整以下配置(根据你的模型字段调整):
# 如果以邮箱作为登录标识 ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email'
2. 排查代码中EmailAddress的错误调用
错误提示是管理器对象被误当作实例访问is_verified属性,检查自定义代码(如信号、序列化器)中的用法:
- 错误写法:
EmailAddress.objects.is_verified - 正确写法:先获取实例再访问属性
email_address = EmailAddress.objects.get(user=request.user) is_verified = email_address.is_verified
3. 确认依赖版本兼容性
检查dj-rest-auth、django-allauth和Django的版本是否匹配,部分版本组合存在API差异。可参考官方文档确认兼容版本,必要时调整依赖版本。
4. 验证INSTALLED_APPS顺序
确保django.contrib.sites在allauth之前,dj_rest_auth.registration在allauth.account之后(当前配置已符合要求,可忽略此步)。
内容的提问来源于stack exchange,提问作者ark948
相关产品推荐
相关产品推荐

