Django用户模型,其中超级用户具有显示名称但不是普通用户

时间:2017-08-05 23:25:08

标签: python django django-models

我试图创建一个自定义django模型,普通用户必须使用名字,姓氏,电子邮件和密码注册,但超级用户必须有另一个名为display name的字段。但是,我不希望我的普通用户能够拥有显示名称。我虽然在实施这个方面遇到了一些麻烦。这是我的模型的外观

from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
# Create your models here.

class UserManager(BaseUserManager):
    def create_user(self, first_name, last_name, email, password, display_name=None):
        user = self.model(
            first_name= first_name,
            last_name = last_name,
            email = email,
            display_name = display_name
        )
        user.set_password(password)
        user.save()
        return user

    def create_superuser(self, first_name, last_name, email, password, display_name):
        user = self.create_user(
            first_name = first_name,
            last_name = last_name,
            email = email,
            password = password,
            display_name = display_name
        )
        user.is_staff = True
        user.is_admin = True 
        user.is_superuser = True
        user.save()
        return user

class User(AbstractBaseUser, PermissionsMixin):
    first_name = models.CharField(max_length=255)
    last_name = models.CharField(max_length=255)
    email = models.EmailField(unique=True)
    display_name = models.CharField(unique=True, max_length=255)
    date_joined = models.DateTimeField(auto_now=True)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    objects = UserManager()

    USERNAME_FIELD = "email"
    REQUIRED_FIELDS = ["first_name", "last_name", "display_name"]

    def __str__(self):
        return self.email

    def get_short_name(self):
        return self.email

    def get_long_name(self):
        return ("{} {} - {}".format(self.first_name, self.last_name, self.email))

问题是,当我创建普通用户时,它仍然要求显示名称。此外,当我创建一个超级用户时,它接受显示名称而不检查它是否已经存在,然后在它保存之前它给了我以下错误

Traceback (most recent call last):
  File "C:\Users\uzman\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\backends\utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File "C:\Users\uzman\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\backends\sqlite3\base.py", line 328, in execute
    return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: UNIQUE constraint failed: accounts_user.display_name

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Users\uzman\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\__init__.py", line 363, in execute_from_command_line
    utility.execute()
  File "C:\Users\uzman\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\__init__.py", line 355, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Users\uzman\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Users\uzman\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 63, in execute
    return super(Command, self).execute(*args, **options)
  File "C:\Users\uzman\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 330, in execute
    output = self.handle(*args, **options)
  File "C:\Users\uzman\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 183, in handle
    self.UserModel._default_manager.db_manager(database).create_superuser(**user_data)
  File "C:\Users\uzman\Documents\Django\djangoreactredux\accounts\models.py", line 23, in create_superuser
    display_name = display_name
  File "C:\Users\uzman\Documents\Django\djangoreactredux\accounts\models.py", line 14, in create_user
    user.save()
  File "C:\Users\uzman\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\auth\base_user.py", line 80, in save
    super(AbstractBaseUser, self).save(*args, **kwargs)
  File "C:\Users\uzman\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\base.py", line 806, in save
    force_update=force_update, update_fields=update_fields)
  File "C:\Users\uzman\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\base.py", line 836, in save_base
    updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
  File "C:\Users\uzman\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\base.py", line 922, in _save_table
    result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
  File "C:\Users\uzman\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\base.py", line 961, in _do_insert
    using=using, raw=raw)
  File "C:\Users\uzman\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\uzman\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\query.py", line 1063, in _insert
    return query.get_compiler(using=using).execute_sql(return_id)
  File "C:\Users\uzman\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\sql\compiler.py", line 1099, in execute_sql
    cursor.execute(sql, params)
  File "C:\Users\uzman\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\backends\utils.py", line 80, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "C:\Users\uzman\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\backends\utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File "C:\Users\uzman\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\utils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "C:\Users\uzman\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "C:\Users\uzman\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\backends\utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File "C:\Users\uzman\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\backends\sqlite3\base.py", line 328, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: UNIQUE constraint failed: accounts_user.display_name

1 个答案:

答案 0 :(得分:0)

您可以在create_superuser中尝试检查是否存在具有相同显示名称的超级用户并相应地添加。如何尝试:[未测试]

def create_superuser(self, first_name, last_name, email, password, display_name):
    if self.model.objects.filter(display_name = display_name).exists():
        raise ValueError('display name already exists'))

    user = self.create_user(
        first_name = first_name,
        last_name = last_name,
        email = email,
        password = password,
        display_name = display_name
     )
    user.is_staff = True
    user.is_admin = True 
    user.is_superuser = True
    user.save()
    return user