首页 > 解决方案 > 为什么在 Django 中创建超级用户时出现“TypeError”?

问题描述

我正在做一个需要 Django 自定义模型的项目。根据可用的文档,我提出了以下代码库:

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


class AccountManager(BaseUserManager):
    def create_superuser(self, email, password, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)
        extra_fields.setdefault('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)

    def create_user(self, email, password, **extra_fields):
        extra_fields.setdefault('is_staff', False)
        extra_fields.setdefault('is_superuser', False)
        if not email:
            raise ValueError(_('Enter the email before proceeding'))

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


class NewEmployeeProfile(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(unique=True)
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    employee_code = models.IntegerField()
    contact = models.CharField(max_length=10)   

    objects = AccountManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['first_name', 'last_name', 'contact']

    def __str__(self):
        return str(self.email)

我迁移模型没有任何问题。但是,当我尝试创建超级用户时,出现以下错误:

Traceback (most recent call last):
  File ".\manage.py", line 22, in <module>
    main()
  File ".\manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line
    utility.execute()
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\__init__.py", line 395, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 79, in execute
    return super().execute(*args, **options)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 371, in execute
    output = self.handle(*args, **options)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 189, in handle
    self.UserModel._default_manager.db_manager(database).create_superuser(**user_data)
  File "E:\Django_Projects\Employee_Management_System\EmployeePortal\AUTHENTICATION\models.py", line 17, in create_superuser
    return self.create_user(email, password, **extra_fields)
  File "E:\Django_Projects\Employee_Management_System\EmployeePortal\AUTHENTICATION\models.py", line 26, in create_user
    user = self.model(email=email, password=password, **extra_fields)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\base.py", line 501, in __init__
    raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.__name__, kwarg))
TypeError: NewEmployeeProfile() got an unexpected keyword argument 'is_staff'

我确实遇到了几个 stackoverflow 帖子,但没有一个对我有帮助。

请建议,谢谢。

新错误:

ERRORS:
AUTHENTICATION.NewEmployeeProfile.is_superuser: (models.E006) The field 'is_superuser' clashes with the field 'is_superuser' from model 'AUTHENTICATION.newemployeeprofile'.

标签: djangodjango-models

解决方案


您尚未为 is_staff、is_superuser 和 is_active 设置字段

  class NewEmployeeProfile(AbstractBaseUser, PermissionsMixin):
        email = models.EmailField(unique=True)
        first_name = models.CharField(max_length=100)
        last_name = models.CharField(max_length=100)
        employee_code = models.IntegerField()
        contact = models.CharField(max_length=10)
#add this
        is_staff = models.BooleanField(default=False)
        is_superuser = models.BooleanField(default=False)
        is_active = models.BooleanField(default=True)
    
        objects = AccountManager()
    
        USERNAME_FIELD = 'email'
        REQUIRED_FIELDS = ['first_name', 'last_name', 'contact']
    
        def __str__(self):
            return str(self.email)

推荐阅读