Python 在Django 1.6中获取用户配置文件

Python 在Django 1.6中获取用户配置文件,python,django,Python,Django,我按照说明尝试并实例化了一个用户对象,这样我就可以在前端的“我的个人资料”链接中显示用户的详细信息。像这样: User.profile = property(lambda u: UserProfile.objects.get(user=u)[0]) profile = request.user.profile return render(request, 'profiles/index.html', {'profile': profile}) 然而,我越来越 TypeError at /my-

我按照说明尝试并实例化了一个用户对象,这样我就可以在前端的“我的个人资料”链接中显示用户的详细信息。像这样:

User.profile = property(lambda u: UserProfile.objects.get(user=u)[0])
profile = request.user.profile
return render(request, 'profiles/index.html', {'profile': profile})
然而,我越来越

TypeError at /my-profile/

'UserProfile' object does not support indexing

我不完全确定我做错了什么,因为它似乎对另一个线程中的OP有效。

这个
[0]
很奇怪,因为
.get()
总是返回一个
用户配置文件,只要它存在。如果没有,则引发
UserProfile.DoesNotExist
异常

链接到的代码使用
.get\u或\u create()
,它返回一个元组,元组的第一个元素是实例,第二个元素是一个布尔值,表示实例是否是新创建的。您需要第一个元素,即元素0

因此,基本上,您应该将其更改回链接答案使用的内容,获取或创建:

User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0])

是的,我想我忽略了一些显而易见的事情。不粘贴代码就到此为止!谢谢。我可以将个人资料传递给模板吗?例如,当我打印出{{profile.email}}时,我没有得到任何返回。{{profile}}返回“UserProfile对象”。我认为它链接到profile表,而不是auth_user表。用户实例是user,user.profile是profile。您似乎只传递了配置文件。您可能应该传递
{'user':request.user}
,然后您可以使用
{{{user.email}
{{user.profile.your_custom_field}
在模板中。我不是一个真正的专家,因为我们所有的项目仍然在1.3、1.4或1.5上,但是现在可以基于一些基类创建自己的用户对象,所以不需要单独的用户和配置文件。但我不知道这是否是所有情况下的最佳时机。查看来自的文档