Should be a simple answer but I can’t figure out what’s wrong here…
I have a user profile with a couple of simple fields. I’m trying to update them like so:
if data['dob'] != None:
request.user.profile.dob = data['dob']
request.user.profile.save()
This doesn’t seem to have any effect at all though.
p.s. i am using a nice little trick in my UserProfile class that looks like this:
User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0])
Could this be part of the problem?
Think about what happens in your code.
If there’s a
dobin your data, you callrequest.user.profile. This calls your property, which makes a request to the database and gets or creates a Profile instance.Next, you call
request.user.profileagain. Guess what this does? Makes a fresh call to the database, and gets an instance of the Profile again. But of course this is a new instance, even though it’s referring to the same database row, so it won’t have the value fordobyou just set on the last version.Now, potentially you could solve this by storing the profile in a local variable:
But to be honest, I’d drop the whole hacking around with the profile property. It’s going to cause you all sorts of problems.