2016-03-27 39 views
0

嘗試從使用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作爲選項傳遞用戶名。我的代碼片段如下。Python create_user錯誤

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

設置REQUIRED_FIELDS代替REQUIRED_FIELD。這是createsuperuser將會提示的字段名稱列表。它必須包含您的自定義用戶模型中不可空或不可空白的所有字段,因此在您的情況下,您可能還需要包括first_name,last_nametagline

這是well-documented

+0

非常感謝。這是打錯了。我想這是複製和粘貼可以是一件好事。再次感謝你,在未來,我將嘗試仔細檢查我的代碼,以防止在論壇上發佈這樣的愚蠢錯誤:)。 – Courtney