簡體   English   中英

在Django中使用createsuperuser命令時如何添加自定義錯誤消息?

[英]How to add custom error message when using createsuperuser command in Django?

我已經創建了一個自定義用戶模型,我希望電子郵件和用戶名成為唯一字段。 我正在使用電子郵件作為我的主要用戶名字段。 兩者都是獨特的。 問題是,當我創建了一個“ 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

這就是我想要的圖像

這就是我得到的圖像

您可以創建自己的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創建超級用戶。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM