在Django中使用createsuperuser命令时如何添加自定义错误消息?

时间:2019-07-08 09:26:32

标签: django django-models

我已经创建了一个自定义用户模型,我希望电子邮件和用户名成为唯一字段。我正在使用电子邮件作为我的主要用户名字段。两者都是独特的。问题是,当我创建了一个“ createsuperuser”时,如果有人已经收到了电子邮件,我会立即收到一个错误消息,但是在用户名字段的情况下,它会在最后检查唯一条件,从而导致丑陋的Postgres唯一约束失败错误。我希望像电子邮件字段一样立即检查用户名字段。

查看下面的图像。

models.py

from django.contrib.auth.models import AbstractUser, BaseUserManager
from django.db import models
from django.forms import ModelForm
from django.utils.translation import ugettext_lazy as _


class UserManager(BaseUserManager):
    """Define a model manager for User model with no username field."""

    use_in_migrations = True

    def _create_user(self, email, password, **extra_fields):
        """Create and save a User with the given email and password."""
        if not email:
            raise ValueError('The given email must be set')

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

    def create_user(self, email, password=None, **extra_fields):
        """Create and save a regular User with the given email and password."""
        extra_fields.setdefault('is_staff', False)
        extra_fields.setdefault('is_superuser', False)
        return self._create_user(email, password, **extra_fields)

    def create_superuser(self, email, password, **extra_fields):
        """Create and save a SuperUser with the given email and password."""
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', 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)


class User(AbstractUser):
    """User model."""

    username = models.CharField(max_length=255, unique=True, null=False)
    full_name = models.CharField(max_length=255, null=True)
    email = models.EmailField(_('email address'), unique=True)
    confirm = models.BooleanField(default=False)
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username', 'full_name']

    objects = UserManager()

    def __str__(self):
        return self.email

This is what I want image

This is what I am getting image

1 个答案:

答案 0 :(得分:0)

您可以创建自己的django命令来创建超级用户。创建超级用户命令示例可以是:

# your_app/management/commands/create_custom_superuser.py
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand


class Command(BaseCommand):
    def handle(self, *args, **options):
        if not get_user_model().objects.filter(username="admin").exists():
            # you can add some logs here
            get_user_model().objects.create_superuser("admin", "admin@admin.com", "admin")

然后您可以通过python manage.py create_custom_superuser创建超级用户。