Reputation: 555
I've followed the instructions here to try and instantiate a user object so I can display a user's details in a 'My Profile' link on the front end. Like so:
User.profile = property(lambda u: UserProfile.objects.get(user=u)[0])
profile = request.user.profile
return render(request, 'profiles/index.html', {'profile': profile})
However, I'm getting
TypeError at /my-profile/
'UserProfile' object does not support indexing
I'm not entirely sure what I'm doing wrong as it seemed to work for the OP in the other thread.
Upvotes: 0
Views: 186
Reputation: 31250
The [0]
is strange, as .get()
always returns a single UserProfile
, provided it exists. If it doesn't, a UserProfile.DoesNotExist
exception is raised.
The code you linked to uses .get_or_create()
, which returns a tuple, the first element of which is the instance, the second is a boolean that says whether the instance was newly created or not. You want the first of these, that is element 0.
So basically you should change it back to what the linked answer uses, get_or_create:
User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0])
Upvotes: 2