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

Django自定义用户模型创建超级用户触发RecursionError的解决方法

解决Django自定义用户模型创建超级用户的递归错误

错误原因

你的CustomAccountManager.create_superuser方法最后一行错误地调用了自身(self.create_superuser),导致无限递归调用,触发RecursionError。超级用户的创建应该基于普通用户的创建逻辑,只需确保权限字段(is_staff、is_superuser等)被正确设置即可。

修复后的代码

修改CustomAccountManager类的create_superuser方法,将递归调用改为调用create_user:

class CustomAccountManager(BaseUserManager):
    def create_superuser(self, user_name, email, first_name, last_name, phone, password, **other_fields):

        other_fields.setdefault('is_staff', True)
        other_fields.setdefault('is_superuser', True)
        other_fields.setdefault('is_active', True)

        if other_fields.get('is_staff') is not True:
            raise ValueError('Superuser must be assigned to is_staff=True.')
        if other_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must be assigned to is_superuser=True.')

        # 改为调用create_user方法,而非自身
        return self.create_user(
            email=email, 
            user_name=user_name, 
            first_name=first_name, 
            last_name=last_name,
            phone=phone, 
            password=password, 
            **other_fields
        )

    def create_user(self, user_name, email, first_name, last_name, phone, password, **other_fields):

        if not email:
            return TypeError(_('Please provide an email address'))

        email = self.normalize_email(email)
        user = self.model(
            email=email, 
            user_name=user_name, 
            first_name=first_name, 
            last_name=last_name, 
            phone=phone,
            **other_fields
        )
        user.set_password(password)
        user.save()

        return user

额外注意事项

  • 确保Users模型的REQUIRED_FIELDS包含了创建用户时必须的字段,与create_user、create_superuser的参数匹配。
  • 运行createsuperuser命令前,确保已经执行过数据库迁移(python manage.py makemigrations和python manage.py migrate)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 19:20:49