【问题标题】:Error: You are trying to add a non-nullable field 'password' to account without a default during Django migrations错误:您正在尝试在 Django 迁移期间将不可为空的字段“密码”添加到没有默认值的帐户
【发布时间】:2016-05-09 06:34:28
【问题描述】:

我打算在 Django 应用程序中构建自定义用户模型,而不是使用内置的。

models.py

from django.contrib.auth.models import AbstractBaseUser
from django.db import models
from django.contrib.auth.models import BaseUserManager

class AccountManager(BaseUserManager):
    def create_user(self, email, password=None, **kwargs):
       if not email:
           raise ValueError('Users must have a valid email address.')

       if not kwargs.get('username'):
          raise ValueError('Users must have a valid username.')

       account = self.model(
          email=self.normalize_email(email),
          username=kwargs.get('username')
       )

       account.set_password(password)
       account.save()

       return account

    def create_superuser(self, email, password, **kwargs):
        account = self.create_user(email, password, **kwargs)

        account.is_admin = True
        account.save()

        return account

class Account(AbstractBaseUser):
    email = models.EmailField(unique=True)
    username = models.CharField(max_length=40, unique=True)

    first_name = models.CharField(max_length=40, blank=True)
    last_name = models.CharField(max_length=40, blank=True)
    tagline = models.CharField(max_length=140, blank=True)

    is_admin = models.BooleanField(default=False)

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    objects = AccountManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']

    def __unicode__(self):
        return self.email

    def get_full_name(self):
        return ' '.join([self.first_name, self.last_name])

    def get_short_name(self):
        return self.first_name

当我运行 python manage.py makemigrations 命令时,我收到以下错误:

You are trying to add a non-nullable field 'password' to account
without a default; we can't do that (the database needs something to 
populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows)
2) Quit, and let me add a default in models.py

注意,我在 settings.py

中添加了这个
AUTH_USER_MODEL = 'authentication.Account'

顺便说一句,该应用程序称为身份验证。

我该如何解决这个问题?谢谢

【问题讨论】:

    标签: python django django-users


    【解决方案1】:

    您收到的错误来自数据库。当该列已有行时,您不能创建没有默认值的不可为空的列。

    在运行此迁移之前,您需要为密码字段设置默认值或删除该表中已有的所有用户。

    【讨论】:

    • 他正在运行 makemigrations 而不是迁移 - 如果您在 makemigrations 期间遇到此错误,通常意味着您的迁移文件夹中已经有其他迁移文件,在这种情况下,在身份验证/迁移中。为了以这种方式使用 AbstractBaseUser,他应该在他的第一次迁移中添加它以避免该错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-12
    • 1970-01-01
    • 1970-01-01
    • 2016-01-04
    • 2018-06-10
    • 2015-09-30
    • 2020-06-03
    相关资源
    最近更新 更多