Django在控制台中创建了超级用户错误

时间:2018-03-09 12:00:01

标签: django

我使用两个应用(自定义用户客户端)启动新项目。在 customuser 中,我重新定义默认用户模型,在客户端中,将UserTrofile与OneToOne字段一起设置为User。然后我跑

from selenium import webdriver

driver = webdriver.Chrome(executable_path='/path/to/chromedriver')
driver.get('https://www.google.co.in')
print("Page Title is : %s" %driver.title)
driver.quit()

在这一点上都好 发髻然后我跑

makemigartions customuser
makemigrations client
migrate

出现错误

createsuperuser

customuser / models.py

return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: NOT NULL constraint failed: client_profile.position_id

的客户机/ models.py

from django.contrib.auth.models import AbstractUser, BaseUserManager

from django.db import models
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 = None
    email = models.EmailField(_('email address'), unique=True)
    phone = models.CharField(max_length=20, blank=True)


    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    objects = UserManager()

帮助理解为什么会发生这种情况并解决此问题。

1 个答案:

答案 0 :(得分:2)

您收到错误是因为您创建的用户没有设置position。如果在数据库中允许null,则需要设置null=True

class Profile(models.Model):
    ...
    position = models.ForeignKey('Position',blank=True, null=True)

完成此操作后,您需要创建迁移并迁移以删除数据库中的NOT NULL约束。