错误:您正在尝试在Django迁移期间向帐户添加不可为空的字段“密码”而没有默认值

时间:2016-01-31 21:43:09

标签: python django django-users

我想在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'

该应用程序称为身份验证btw。

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

1 个答案:

答案 0 :(得分:2)

您获得的错误来自数据库。如果该列已有行,则无法在没有默认值的情况下创建不可为空的列。

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