Django - 属性错误

Posted

技术标签:

【中文标题】Django - 属性错误【英文标题】:Django - AttributeError 【发布时间】:2018-05-01 17:23:25 【问题描述】:

我创建了我的自定义用户模型。在进行迁移时,我得到了一个 AtrributeError

from django.db import models
from time import timezone
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.core.mail import send_mail
from django.utils.http import urlquote
from django.utils.translation import ugettext_lazy as _


class CustomUsermanager(BaseUserManager):
    def _create_user(self, is_anonymous, first_name, last_name, email, username, password, home_address, user_type, image_path):
        now = timezone.now()

        if not email:
            raise ValueError('The gives emial must be set')

        email = self.normalize_email(email)
        user = self.model(
            is_anonymous=is_anonymous,
            first_name=first_name,
            last_name=last_name,
            email=email,
            username=username,
            home_address=home_address,
            user_type=user_type,
            image_path=image_path,
            created_time=now,
            last_login=now
        )

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_a_admin(self, first_name, last_name, email, username, password, home_address, image_path):
        return self._create_user(1, first_name, last_name, email, username, password, home_address, 0, image_path)

    def create_a_nonanonymous_patient(self, first_name, last_name, email, username, password, home_address, image_path):
        return self._create_user(0, first_name, last_name, email, username, 1, password, home_address, 1, image_path)

    def create_an_anonymous_patient(self, first_name, last_name, email, username, password, home_address, image_path):
        return self._create_user(1, first_name, last_name, email, username, 1, password, home_address, 1, image_path)

    def create_a_nonanonymous_helper(self, first_name, last_name, email, username, password, home_address, image_path):
        return self._create_user(0, first_name, last_name, email, username, 2, password, home_address, 2, image_path)

    def create_an_anonymous_helper(self, first_name, last_name, email, username, password, home_address, image_path):
        return self._create_user(1, first_name, last_name, email, username, 2, password, home_address, 2, image_path)

    def create_a_prof(self, first_name, last_name, email, username, password, home_address, image_path):
        return self._create_user(0, first_name, last_name, email, username, 3, password, home_address, 3, image_path)


class CustomUser(AbstractBaseUser):
    is_anonymous = models.BooleanField()
    username = models.CharField(max_length=255, unique=True)
    first_name = models.CharField(max_length=255, blank=True)
    last_name = models.CharField(max_length=255, blank=True)
    email = models.EmailField(blank=True, unique=True)
    home_address = models.CharField(max_length=255, blank=True)
    user_type = models.IntegerField(1)
    image_path = models.CharField(max_length=500, blank=True)
    created_time = models.TimeField()

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['username', 'home_address', 'first_name', 'last_name', 'user_type']

    objects = CustomUsermanager()

    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')

    def get_absolute_url(self):
        return '/users/%s/' % urlquote(self.email)

    def get_full_name(self):
        full_name = '%s %s' % (self.first_name, self.last_name)
        return full_name.strip()

    def get_short_name(self):
        return self.first_name

    def get_email_user(self, subject, message, from_email=None):
        send_mail(subject, message, from_email, [self.email])

例外是:

Traceback(最近一次调用最后一次):

文件“manage.py”,第 22 行,在 execute_from_command_line(sys.argv) 中

文件“C:\Users\Nutzer\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management__init__.py”,第 363 行,在 execute_from_command_line 实用程序.execute()

文件“C:\Users\Nutzer\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management__init__.py”,第 355 行,在执行中 self.fetch_command(subcommand).run_from_argv(self.argv)

文件“C:\Users\Nutzer\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py”,第 283 行,在 run_from_arg v self.execute(*args, **cmd_options)

文件“C:\Users\Nutzer\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py”,第 327 行,在执行中 self.check()

文件“C:\Users\Nutzer\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py”,第 359 行,检查 include_deployment_checks=include_deployment_checks,

文件“C:\Users\Nutzer\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py”,第 346 行,在 _run_checks 返回 checks.run_checks(**kwargs)

文件“C:\Users\Nutzer\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\checks\registry.py”,第 81 行,在 run_checks new_errors = 检查(app_configs=app_configs)

文件“C:\Users\Nutzer\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\auth\checks.py”,第 77 行,在 check_user_mod 埃尔 if isinstance(cls().is_anonymous, MethodType):

文件“C:\Users\Nutzer\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\auth\base_user.py”,第 68 行,在 init super(AbstractBaseUser, self).init(*args, **kwargs)

文件“C:\Users\Nutzer\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\base.py”,第 557 行,在 init _setattr(self, field.attname, val)

AttributeError: 无法设置属性

谁能指出哪里错了?

【问题讨论】:

您正在运行什么迁移? minimal reproducible example @HåkenLid 我不明白你的意思。我只是做“python manage.py makemigrations” 我很困惑为什么你有一个名为is_anonymous 的模型字段。这可能是导致此问题的原因,因为这应该是AbstractBaseUser 中的只读属性,始终返回False。尝试删除该字段并运行 makemigrations。 我可以确认@HåkenLid 的发现。要查看 AbstractBaseUser 类的属性和方法,请参见此处:github.com/django/django/blob/master/django/contrib/auth/… @noahandthewhale,谢谢!这真是巧合! 【参考方案1】:
user = self.models(
        is_anonymous=is_anonymous,
        first_name=first_name,
        last_name=last_name,
        email=email,
        username=username,
        home_address=home_address,
        user_type=user_type,
        image_path=image_path,
        created_time=now,
        last_login=now
    )

替换模型

【讨论】:

以上是关于Django - 属性错误的主要内容,如果未能解决你的问题,请参考以下文章

Django 教程:通用视图。属性错误

Django Rest框架属性错误

Django 错误:“'ChoiceField' 对象没有属性 'is_hidden'”

如何从 django 中的表单错误属性中获取值

Django-taggit-templatetags2 属性错误

尝试向 API 发送 POST 请求时出现属性错误 - Django