updating user profile fields django
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开发者_如何学C 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 dob
in your data, you call request.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.profile
again. 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 for dob
you just set on the last version.
Now, potentially you could solve this by storing the profile in a local variable:
profile = request.user.profile
profile.dob = data['dob']
profile.save()
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.
It might be easier to use the suggested method of tying a profile to a django user:
https://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users
In the meantime, remove the [0] at the end of the UserProfile.objects.get_or_create(user=u) as that method only returns a single object regardless
精彩评论