【问题标题】:django extending User with UserProfile: User has no userprofiledjango 使用 UserProfile 扩展用户:用户没有用户配置文件
【发布时间】:2015-10-05 19:54:44
【问题描述】:

我设置了一个 UserProfile 类,并通过 Django 管理控制台创建了一个具有用户配置文件的用户,但我似乎无法从我的视图中访问该用户配置文件。错误是:RelatedObjectDoesNotExist at /mcadb/ 用户没有用户资料。关于我在这里缺少什么的任何想法?我看过示例,但看不到。当我加载视图时,错误似乎在 test = user.userprofile 视图中。谢谢。

models.py

class UserProfile(models.Model):
     my_id = models.CharField(max_length=8)
     user = models.OneToOneField(User)

views.py

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

@login_required
def index(request):
    user = request.user
    test = user.userprofile

【问题讨论】:

  • 尝试使用:test = user.userprofile_set
  • @Gocht,不,OneToOneField 没有映射到 _set。此外,如果名称错误,那将是一个 AttributeError。 @Carrie,尝试一些调试。在您的测试行上方添加print(user); print UserProfile.objects.all()) 以在控制台上查看该用户是否确实存在 UserProfile 对象。如果没有,请尝试创建新的用户和用户配置文件,使用新用户登录并查看问题是否存在。
  • @gbs,感谢您的建议。我正在 AWS 上开发,所以我不确定 print 是否应该工作,但似乎没有。但是我可以将 {{ user.userprofile.my_id }} 添加到我的索引视图模板中,并且可以正确打印。所以用户和用户配置文件存在。
  • @gbs,我发现了问题。在我的实际代码中(我不得不在这里重新输入,因为我对在 AWS 中进行开发非常陌生),在 User 的导入语句之前,我有 UserProfile 的导入语句。切换它们似乎已经解决了这个问题。非常感谢你帮助我到达那里。 :)
  • 别担心@Carrie,很高兴听到你解决了!

标签: django


【解决方案1】:

在我的实际代码中(我不得不在这里重新键入,因为我对在 AWS 中进行开发非常不熟悉),在用户的导入语句之前,我有 UserProfile 的导入语句。切换它们,以匹配我在这里发布的内容,似乎已经解决了这个问题。因此,吸取的教训:import 语句的顺序很重要。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-26
    • 1970-01-01
    • 2012-03-11
    • 2013-06-19
    • 2015-07-08
    • 1970-01-01
    • 2012-10-02
    • 1970-01-01
    相关资源
    最近更新 更多