繁体   English   中英

在Django 1.6中获取用户个人资料

[英]Getting a user profile in Django 1.6

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

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

我不能完全确定我在做什么错,因为它似乎可以在另一个线程中运行。

[0]很奇怪,因为.get()始终返回单个UserProfile (如果存在)。 如果不是,则会引发UserProfile.DoesNotExist异常。

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

因此,基本上,您应该将其改回链接的答案使用的类型,即get_or_create:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM