【问题标题】:django why getting this error 'RelatedManager' object has no attribute 'email_confirmed'?django 为什么得到这个错误'RelatedManager'对象没有属性'email_confirmed'?
【发布时间】:2024-01-20 10:03:01
【问题描述】:

当我使用user.email_confirmed 时,我没有收到任何错误,但是当我使用user.userprofile.email_confirmed 时出现 RelatedManager 错误。为什么我在尝试从 userprofile 模型中获取用户详细信息时收到此错误?

这是我的代码:

class UserManagement(AbstractUser):
          is_blog_author = models.BooleanField(default=False)
          is_editor = models.BooleanField(default=False)
          is_subscriber = models.BooleanField(default=False)
          is_customer = models.BooleanField(default=False)
          email_confirmed = models.BooleanField(default=False) #there is no error when obtaining email_confirmed object from abstract user model.  

class UserProfile(models.Model):
      user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name="userprofile")
      email_confirmed = models.BooleanField(default=False)


#I am using this for email verification 
class AccountActivationTokenGenerator(PasswordResetTokenGenerator):
    def _make_hash_value(self, user, timestamp):
        return (
            six.text_type(user.pk) + six.text_type(timestamp) +
            six.text_type(user.userprofile.email_confirmed) #error rising for this line 
            #six.text_type(user.email_confirmed) #I am not getting error if I use this line 
        )

account_activation_token = AccountActivationTokenGenerator()

views.py

....others code 
if user is not None and account_activation_token.check_token(user, token):
            user.userprofile.email_confirmed = True #why it's not working and rising error? 
            #user.email_confirmed = True #it's working 
            user.save()
            .....others code 

【问题讨论】:

  • UserProfile 使用 ForeignKey,而不是 OneToOneField,因此每个用户可以有多个 UserProfile 对象。因此,您需要先将user.userprofile 查询集过滤为单个对象,然后才能使用它。另见:*.com/questions/5870537/…
  • @Nick ODell 我应该使用 user.userprofile.filter(email_confirmed = True) 六个吗?你能告诉我哪个查询集适合user.userprofile.email_confirmeduser.userprofile.email_confirmed = True

标签: python python-3.x django


【解决方案1】:

@Nick ODell 告诉我我需要使用过滤器。

这两个查询集出现了问题: user.userprofile.email_confirmeduser.userprofile.email_confirmed = True 更改主题后

user.userprofile.filter(email_confirmed=False)user.userprofile.filter(email_confirmed=False).update(email_confirmed=True) 我的问题解决了。

【讨论】: