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

使用Djoser实现用户注册时出现NoneType无is_active属性错误

问题:Djoser用户注册返回500错误:AttributeError: 'NoneType' object has no attribute 'is_active'

尝试用Djoser实现用户注册功能,确认请求体已传入所有正确数据,但仍返回500错误,报错信息为AttributeError: 'NoneType' object has no attribute 'is_active'。已尝试重写BaseUserAdmin中的list_display和list_filter,也尝试调整模型中is_active属性的位置,问题依旧。

models.py

from django.contrib.auth.models import AbstractUser, AbstractBaseUser, PermissionsMixin, BaseUserManager
from django.db import models
from django.utils import timezone
from django.utils.translation import gettext_lazy as _


# 管理用户及超级用户创建
class UserAccountManager(BaseUserManager):
    def create_user(self, email, password=None, **extra_fields):
        if not email:
            raise ValueError('Users must provide an email address.')

        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)                          
        user.set_password(password)
        user.save()

    def create_superuser(self, email, password=None, **extra_fields):
        extra_fields.setdefault('is_active', True)
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)

        if extra_fields.get('is_active') is not True:
            raise ValueError('Superuser must have is_active=True.')
        if extra_fields.get('is_staff') is not True:
            raise ValueError('Superuser must have is_staff=True.')
        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')

        return self.create_user(email, password, **extra_fields)


class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(max_length=255, unique=True)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)

    objects = UserAccountManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    def __str__(self):
        return self.email

serializers.py

from djoser.serializers import UserCreateSerializer
from django.contrib.auth import get_user_model

User = get_user_model()


class UserCreateSerializer(UserCreateSerializer):
    class Meta(UserCreateSerializer.Meta):
        model = User
        fields = ('id', 'email', 'password')

报错栈信息

Traceback (most recent call last):
  File "/Users/law/.local/share/virtualenvs/backend-2t9m5bj9/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
               ^^^^^^^^^^^^^^^^^^^^^
  File "/Users/law/.local/share/virtualenvs/backend-2t9m5bj9/lib/python3.11/site-packages/django/core/handlers/base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/law/.local/share/virtualenvs/backend-2t9m5bj9/lib/python3.11/site-packages/django/views/decorators/csrf.py", line 56, in wrapper_view
    return view_func(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/law/.local/share/virtualenvs/backend-2t9m5bj9/lib/python3.11/site-packages/rest_framework/viewsets.py", line 125, in view
    return self.dispatch(request, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/law/.local/share/virtualenvs/backend-2t9m5bj9/lib/python3.11/site-packages/rest_framework/views.py", line 509, in dispatch
    response = self.handle_exception(exc)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/law/.local/share/virtualenvs/backend-2t9m5bj9/lib/python3.11/site-packages/rest_framework/views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/Users/law/.local/share/virtualenvs/backend-2t9m5bj9/lib/python3.11/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
    raise exc
  File "/Users/law/.local/share/virtualenvs/backend-2t9m5bj9/lib/python3.11/site-packages/rest_framework/views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/law/.local/share/virtualenvs/backend-2t9m5bj9/lib/python3.11/site-packages/rest_framework/mixins.py", line 19, in create
    self.perform_create(serializer)
  File "/Users/law/.local/share/virtualenvs/backend-2t9m5bj9/lib/python3.11/site-packages/djoser/views.py", line 132, in perform_create
    user = serializer.save(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/law/.local/share/virtualenvs/backend-2t9m5bj9/lib/python3.11/site-packages/rest_framework/serializers.py", line 212, in save
    self.instance = self.create(validated_data)
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/law/.local/share/virtualenvs/backend-2t9m5bj9/lib/python3.11/site-packages/djoser/serializers.py", line 40, in create
    user = self.perform_create(validated_data)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/law/.local/share/virtualenvs/backend-2t9m5bj9/lib/python3.11/site-packages/djoser/serializers.py", line 50, in perform_create
    user.is_active = False
    ^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'is_active'
[31/Oct/2023 20:55:55] "POST /auth/users/ HTTP/1.1" 500 111290

解决方案

问题根源在UserAccountManager.create_user方法:该方法没有返回创建的user对象。Djoser的serializer调用perform_create后,会尝试修改返回的user实例的is_active属性,但因为create_user返回None,直接触发了AttributeError。

修改create_user方法,添加返回语句:

def create_user(self, email, password=None, **extra_fields):
    if not email:
        raise ValueError('Users must provide an email address.')

    email = self.normalize_email(email)
    user = self.model(email=email, **extra_fields)                          
    user.set_password(password)
    user.save()
    return user  # 新增这一行

修改后,create_user会返回创建的用户实例,Djoser就能正常修改is_active属性。

另外,确保在settings.py中正确配置自定义用户模型:

AUTH_USER_MODEL = '你的应用名.User'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 05:25:21