Ошибка при создании суперпользователя Не удалось выполнить ограничение NOT NULL

.equals() сравнивает данные в классе (при условии, что функция реализована). == сравнивает местоположения указателя (расположение объекта в памяти).

== возвращает true, если оба объекта (NOT TALKING OF PRIMITIVES) указывают на экземпляр SAME. .equals() возвращает true, если два объекта содержат одни и те же данные equals() Versus == в Java

Это может вам помочь.

0
задан marcos 17 January 2019 в 09:43
поделиться

1 ответ

Есть два возможных способа сделать это. Вы можете добавить roll и contact_no в require_fields, чтобы команда superuser запрашивала их, или вы можете использовать пользовательский usermanager для перезаписи вашего метода create_superuser .

Решение 1

Добавить roll и contact_no в REQUIRED_FIELDS

class Student(AbstractUser):
    email = models.EmailField(unique=True)
    roll = models.CharField(max_length=200, blank=False)
    contact_no = models.DecimalField(
        max_digits=10, decimal_places=0, blank=False)
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['roll', 'contact_no',] # By doing so create superuser command will ask their input

Решение 2

Добавить пользовательский менеджер пользователя и перезаписать метод create_superuser

from django.contrib.auth.models import BaseUserManager, AbstractUser
from django.db import models
from django.utils import timezone

class UserManager(BaseUserManager):
      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 email must be set')
          if not password:
                raise ValueError('The password 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_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)
          extra_fields.setdefault('roll', YOUR DESIRE VALUE )
          extra_fields.setdefault('contact_no', YOUR DESIRE VALUE)
          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.')
          super_user = self._create_user(email, password, **extra_fields)
          return super_user

class Student(AbstractUser):
     email = models.EmailField(unique=True)
     roll = models.CharField(max_length=200, blank=False)
     contact_no = models.DecimalField(
       max_digits=10, decimal_places=0, blank=False)
     objects = UserManager()
     USERNAME_FIELD = 'email'
0
ответ дан marcos 17 January 2019 в 09:43
поделиться
Другие вопросы по тегам:

Похожие вопросы: