【问题标题】:Django get_profile() method not working on extended User modelDjango get_profile() 方法不适用于扩展用户模型
【发布时间】:2012-11-01 18:24:30
【问题描述】:

我在一个名为 user_profile 的应用中有一个模型,如下所示:

from django.db import models
from django.contrib.auth.models import User

class UserProfile(models.Model):
    user = models.OneToOneField(User)

    def __unicode__(self):
        return self.user.username

在我的设置中:

AUTH_PROFILE_MODULE = 'user_profile.UserProfile'

但如果我尝试:

u = UserProfile.objects.get(pk=1)
p = u.get_profile()

我收到以下错误:

AttributeError: 'UserProfile' object has no attribute 'get_profile'

我在这里错过了什么?

任何帮助将不胜感激。

【问题讨论】:

    标签: python django django-models


    【解决方案1】:

    对于按照旧文档获取此错误的任何其他人,get_profile() 在 django 1.7 中已被贬值。

    相反,您可以从用户那里访问用户配置文件,如下所示..

    u_p = user.userprofile
    

    其中userprofile 是您的UserProfile 类的名称

    您也可以通过点击右下角的所需版本来更改为使用较新的文档

    【讨论】:

    • 谢谢。这对我很有帮助。
    【解决方案2】:

    呃,您正在尝试获取 UserProfile 的用户配置文件。我希望您的意思是获取一个用户,然后调用get_profile()

    【讨论】:

    • 好的。我想通过指定AUTH_PROFILE_MODULE = 'user_profile.UserProfile' 我可以访问get_profile() 方法。另外,如果我在模板中执行{{ request.user.get_profile.username }},我什么也得不到。
    • 所以,如果我这样做 {{ user.get_profile.user }} 模板会显示用户名。但我做不到{{ user.get_profile.username }}{{ user.get_profile.email }}。这是为什么呢?
    • 你为什么想做这些事情?电子邮件和用户名是用户模型上的字段,这是您开始使用的!为什么要从用户转到用户配置文件,然后再返回用户?啊!
    • 因为如果我在某个时候展开 UserProfile,我可能想要获取那些特定字段和通用字段,例如电子邮件。我虽然所有这些都可以通过get_profile() 联系到。
    • 我应该如何在模板中获取电子邮件变量?好的,我猜{{ user.email }} 有效。
    【解决方案3】:

    我使用的是 Django 1.8,.userprofile 抛出错误。

    为了解决这个问题,因为我在 Django 1.3 中设置了配置文件,升级到 1.8 后,我只是将 .get_profile() 更改为 profile 并且它可以工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-12
      • 2011-02-28
      • 2013-12-06
      • 2018-01-21
      相关资源
      最近更新 更多