【问题标题】:You are trying to add a non-nullable field 'password' to user without a default; we can't do that您正在尝试在没有默认值的情况下向用户添加不可为空的字段“密码”;我们不能那样做
【发布时间】:2019-12-02 10:23:12
【问题描述】:

我正在 django 中构建一个自定义 User 类,用于创建注册应用程序,每次尝试进行迁移时,我都会不断收到上述错误。据我所知,我的代码是这里的 django 文档。我还将 AUTH_USER_MODEL 正确放置在我的设置配置中。这是我的models.py

# from __future__ import unicode_literals
from django.contrib.auth.models import AbstractUser
from django.contrib.auth.base_user import BaseUserManager
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.core.validators import RegexValidator

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)
        if password:
            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):
    email = models.EmailField(_('email address'), unique=True, default='email')
    username = None
    first_name = models.CharField(max_length=20, blank=False, null=False, default='first_name')
    last_name = models.CharField(max_length=20, blank=False, null=False, default='last_name')
    phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+91 ...'")
    phone_no = models.CharField(validators=[phone_regex], max_length=17,blank=False, default='phone_number')
    # email_validator = EmailValidator(message='Invalid email
    # address',code=None,whitelist=None)

    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    is_admin = models.BooleanField(default=False)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []
    # Email & Password are required by default
    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')

    objects = UserManager()

    def get_full_name(self):
        return self.email

    def get_short_name():
        return self.email

    def __str__(self):
        return self.email

    def has_perm(self, perm, obj=None):
        # does user have a specific permission
        return True

    def has_module_pers(self, app_label):
        # does user have permissions to view the app 'app_label'
        return True

    @property
    def is_admin(self):
        return self.is_admin

    @property
    def is_active(self):
        return self.is_active

# Create your models here.""

【问题讨论】:

  • 问题出在create_user(self, email, password=None, **extra_fields):创建时不能有空密码
  • 我已经从 create_user(self, email, password=None, **extra_fields) 中删除了 None:但仍然是同样的问题
  • 你也可以在问题中添加你的用户模型吗?
  • 这里只有请向下滚动
  • 我明白了,下次请将每个部分的每种代码格式分开,以便更容易注意到,如果您可以尝试删除数据库中存在的其他用户并设置密码回到原来的create_user(self, email, password=None, **extra_fields)

标签: django python-3.x


【解决方案1】:

我从数据库中删除了现有用户,并从迁移文件夹中删除了以前的迁移文件。再次迁移后问题已解决

【讨论】:

    猜你喜欢
    • 2021-11-16
    • 2021-09-06
    • 2021-06-21
    • 2016-01-04
    • 2020-06-03
    • 2017-10-09
    • 1970-01-01
    • 2020-07-12
    • 2020-03-28
    相关资源
    最近更新 更多