[英]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.