Python create_user error

时间:2016-03-27 12:16:46

标签: python django

尝试使用Django 1.7.1从命令行调用create_superuser命令时收到错误ValueError: Users must have a valid username。我正在按照教程创建自定义用户模型,并将电子邮件字段设置为USERNAME_FIELD。它没有提示我输入用户名,我尝试将用户名作为选项python manage.py createsuperuser --username=someusernamepython manage.py createsuperuser username=someusername传递。我的代码片段如下。

models.py

# Create your models here.
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):
    """docstring for Account"""
    email = models.EmailField(unique=True)
    username = models.CharField(max_length=40, unique=True)

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

    is_admin = models.BooleanField(default=False)

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

    objects = AccountManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELD = ['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

在settings.py文件中,我已将身份验证添加到已安装的应用列表中,并且已将AUTH_USER_MODEL定义为authentication.Account

1 个答案:

答案 0 :(得分:1)

设置REQUIRED_FIELDS而不是REQUIRED_FIELD。这是createsuperuser将提示的字段名称列表。它必须包含您的自定义用户模型中不可空/不可空白的所有字段,因此在您的情况下,您可能还想包括first_namelast_nametagline

这是well-documented