Error: You are trying to add a non-nullable field 'password' to account without a default during Django migrations

牧云@^-^@ 提交于 2021-02-11 15:40:52

问题


I am tying to build a custom user model in a Django app, instead of using the built-in one.

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

When I run the python manage.py makemigrations commands, I get the following error:

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

Note, I have added this in settings.py

AUTH_USER_MODEL = 'authentication.Account'

The app is called authentication btw.

How do I fix this? Thanks


回答1:


The error you're getting is from the database. You can't create a non-nullable column without a default value when there are already rows for that column.

You would either need to set a default for the password field or delete all the users you already have in that table before running this migration.



来源:https://stackoverflow.com/questions/35119855/error-you-are-trying-to-add-a-non-nullable-field-password-to-account-without

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!