'ProfileManager'对象没有属性'username'

时间:2013-10-11 12:50:24

标签: python django django-models django-users

我正在尝试使用用户名创建一个自定义用户模型,其中包含唯一且必需的电子邮件字段,我正在通过以下示例进行操作: https://docs.djangoproject.com/en/dev/topics/auth/customizing/#a-full-example 这是我的models.py:

from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from utils.upload import get_upload_path

class ProfileManager(BaseUserManager):
    def create_user(self, username, email, password=None):
        if not username:
            raise ValueError("User must have a username.")
        if not email:
            raise ValueError("User must have an email address.")
        user = self.model(
            username = self.username,
            email = self.normalize_email(email),
        )
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, username, email, password):
        user = self.create_user(username, email, password=password)
        user.is_admin = True
        user.save(using=self._db)
        return user

class Profile(AbstractBaseUser):
    username = models.CharField(db_index=True, unique=True, max_length=30, verbose_name=u"username")
    email = models.EmailField(db_index=True, unique=True, max_length=255, verbose_name=u"e-mail address")
    # Profile information
    first_name = models.CharField(blank=True, null=True, max_length=30, verbose_name=u"first name")
    last_name = models.CharField(blank=True, null=True, max_length=30, verbose_name=u"last name")
    city = models.CharField(blank=True, null=True, max_length=30, verbose_name=u"city")
    country = models.CharField(blank=True, null=True, max_length=30, verbose_name=u"country")
    # Forum information
    avatar = models.ImageField(blank=True, null=True, upload_to=get_upload_path("avatars"), max_length=255)
    signature = models.TextField(blank=True, null=True, verbose_name=u"signature")
    # Contact info
    icq = models.CharField(blank=True, null=True, max_length=16, verbose_name=u"ICQ number")

    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)

    objects = ProfileManager()

    USERNAME_FIELD = "username"
    REQUIRED_FIELDS = ["email"]

    def get_full_name(self):
        return self.username

    def get_short_name(self):
        return self.username

    def __unicode__(self):
        return self.username

    def has_perm(self, perm, obj=None):
        return True

    def has_module_perms(self, app_label):
        return True

    @property
    def is_staff(self):
        return self.is_admin

当我第一次运行python manage.py syncdb命令,创建新数据库并创建超级用户时,我收到此错误:

'ProfileManager' object has no attribute 'username'

1 个答案:

答案 0 :(得分:1)

您的错误在这里:

    user = self.model(
        username = self.username,

经理没有用户名 - 你的意思是

    user = self.model(
        username = username,

因为您将其作为参数传递。完整的追溯会使这一点显而易见。