Django:使用自定义用户模型创建超级用户 [英] Django: Creating a superuser with a custom User model

查看:131
本文介绍了Django:使用自定义用户模型创建超级用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I replaced the built-in auth user model with a custom model that requires email to sign in. What happens now though, is that I can't create a superuser.

这是我的模特:

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()

我用它来创建超级用户:

I use this to create the superuser:

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

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

and then I get my prompts(First name, Last name, Password) and this error:

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

不确定,为什么.

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

Also, how can I make the system prompt to create a superuser, when creating a database (like the built in user does)?

提前谢谢!

推荐答案

尝试将PermissionsMixin添加到CustomUser基类:

from django.contrib.auth.models import PermissionsMixin


class CustomUser(AbstractBaseUser, PermissionsMixin):
    ...

这篇关于Django:使用自定义用户模型创建超级用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆