Django:使用自定义用户模型创建超级用户

时间:2013-12-06 14:07:14

标签: django authentication django-models root

我使用需要电子邮件登录的自定义模型替换了内置的auth用户模型。但现在发生的是,我无法创建超级用户。

以下是我的模特:

class CustomUserManager(BaseUserManager):
        def create_user(self, email, first_name, last_name, password=None, 
                                                       ):
                '''
                Create a CustomUser with email, name, password and other extra fields
                '''
                now = timezone.now()
                if not email:
                        raise ValueError('The email is required to create this user')
                email = CustomUserManager.normalize_email(email)
                cuser = self.model(email=email, first_name=first_name,
                                                        last_name=last_name, is_staff=False, 
                            is_active=True, is_superuser=False,
                                                        date_joined=now, last_login=now,)
                cuser.set_password(password)
                cuser.save(using=self._db)
                return cuser

        def create_superuser(self, email, first_name, last_name, password=None, 
                                                           ):
                u = self.create_user(email, first_name, last_name, password, 
                                                           )
                u.is_staff = True
                u.is_active = True
                u.is_superuser = True
                u.save(using=self._db)

                return u

class CustomUser(AbstractBaseUser):
        '''
        Class implementing a custom user model. Includes basic django admin
        permissions and can be used as a skeleton for other models. 

        Email is the unique identifier. Email, password and name are required
        '''
        email = models.EmailField(_('email'), max_length=254, unique=True,
                                                                validators=[validators.validate_email])
        username = models.CharField(_('username'), max_length=30, blank=True)
        first_name = models.CharField(_('first name'), max_length=45)
        last_name = models.CharField(_('last name'), max_length=45)
        is_staff = models.BooleanField(_('staff status'), default=False,
                                help_text=_('Determines if user can access the admin site'))
        is_active = models.BooleanField(_('active'), default=True)
        date_joined = models.DateTimeField(_('date joined'), default=timezone.now)

        objects = CustomUserManager()

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

        def get_full_name(self):
                '''
                Returns the user's full name. This is the first name + last name
                '''
                full_name = "%s %s" % (self.first_name, self.last_name)
                return full_name.strip()

        def get_short_name(self):
                '''
                Returns a short name for the user. This will just be the first name
                '''
                return self.first_name.strip()

我用它来创建超级用户:

python manage.py createsuperuser --email=example@gmail.com

然后我得到我的提示(名字,姓氏,密码)和这个错误:

Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 399, in execute_from_command_line
    utility.execute()
  File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 392, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Library/Python/2.7/site-packages/django/core/management/base.py", line 242, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/Library/Python/2.7/site-packages/django/core/management/base.py", line 285, in execute
    output = self.handle(*args, **options)
  File "/Library/Python/2.7/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 141, in handle
    self.UserModel._default_manager.db_manager(database).create_superuser(**user_data)
  File "/Users/yudasinal1/Documents/Django/git/Django_project_for_EGG/logins/models.py", line 50, in create_superuser
    date_joined=timezone.now(), last_login=timezone.now(),)
  File "/Library/Python/2.7/site-packages/django/db/models/base.py", line 417, in __init__
    raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
TypeError: 'is_superuser' is an invalid keyword argument for this function

不确定,为什么。

另外,在创建数据库时(如内置用户那样),如何让系统提示创建超级用户?

提前致谢!!!

1 个答案:

答案 0 :(得分:13)

尝试将PermissionsMixin添加到CustomUser基类:

from django.contrib.auth.models import PermissionsMixin


class CustomUser(AbstractBaseUser, PermissionsMixin):
    ...