RG5 RG5 - 6 months ago 22
Python Question

Can't update Django 1.9 BooleanField

I have the following model

class UserProfile(models.Model):

user = models.OneToOneField(User, related_name='profile')
force_password_change = models.BooleanField(default=False)


For some reason I am not able to change the BooleanField at all. I would like to do this is in a view without a model form. Here's the output I get from the Django command line

>>> new_user = User.objects.get(username="bob")
>>> new_user
<User: bob>
>>> type(new_user)
<class 'django.contrib.auth.models.User'>
>>> new_user.profile
<UserProfile: bob>
>>> type(new_user.profile)
<class 'accounts.models.UserProfile'>
>>> new_user.profile.force_password_change
False
>>> new_user.profile.force_password_change = True
>>> new_user.save()
>>> new_user.profile.force_password_change
False
>>>


So what am I missing here? I'm sure it's something stupid, but any help would be great.

UPDATE:

Same issue if update the profile field.

>>> new_user.profile.force_password_change
False
>>> new_user.profile.force_password_change = True
>>> new_user.profile.save()
>>> new_user.profile.force_password_change
False
>>>


UPDATE 2:

Tried this also:

>>>
>>> new_user.profile.force_password_change = True
>>> new_user.profile.save()
>>> new_user = User.objects.get(pk=new_user.pk)
>>> new_user.profile.force_password_change
False
>>>


I guess the last bit of useful information I can provide is that I can fully change the force_password_change field through the admin panel. It's like the save action is not happening when I try user.profile.save()? But I'm not getting any errors that I notice.

Answer

Have you tried saving the UserProfile object directly?

p = UserProfile.objects.get(user=new_user)
p.force_change_password = True
p.save()

print new_user.profile.force_change_password

Please excuse my brevity here... I'm typing this on a phone.

Comments