1👍
I’m going to hazard a guess here
def save(self, *args, **kwargs):
...
self.instance.gravatar = (self.cleaned_data['gravatar'] == 'True')
profile = super(ProfileForm, self).save(*args,**kwargs)
return profile
It seems you are using a custom widget, and by the looks of things you need to change the string 'True'
(passed back from the form) to a boolean True
before saving it to the DB. When you call save()
on the next line though, the ModelForm
will overwrite the value you have given self.instance.gravatar
with the data directly from the form’s cleaned_data
:
https://github.com/django/django/blob/master/django/forms/models.py#L351
Also, in __init__
, you don’t need to include
self.fields['gravatar'].initial = self.instance.usesGravatar
as this field is already bound to the model form and will be automatically populated (if the UserProfile
is being edited for example) when you instantiate the form along with an instance in your view.
Finally, in your Meta
, you don’t need to include both excludes
and fields
, one or the other should be fine.
1👍
First of all consider suggestions from @Timmy.
The only thing which else should be noticed is in this line:
profile = super(ProfileForm, self).save(*args,**kwargs)
By default the save
method has commit=True
. Verify that the function which is calling this Form might be sending commit=False
in args
or kwargs
. If yes then you have to manually save the profile profile.save()
before returning because commit=False
means the changes will not reflect to the db.
And why you are allowing user to update both username and email? How you will keep track of the registration process if you are allowing to update both fields? Usually user sign up using their email. Define your criteria which field(username or email) you want to kept unchanged.
Update
Also you are doing one more thing wrong in your save function. You are updating the email, username, firstname and lastname in user taken from instance.user
. But that instance overwritten when profile form default save is call here profile = super(ProfileForm, self).save(*args,**kwargs)
. What you should do is to update those fields using the user = profile.user
The profile
which is returned by the super
. Your save
function should be looked like this:
def save(self, *args, **kwargs):
"""
Update the primary email address on the related User object as well.
"""
profile = super(ProfileForm, self).save(*args,**kwargs)
u = profile.user
u.email = self.cleaned_data['email']
u.username = self.cleaned_data['display_name']
u.first_name = self.cleaned_data['first_name']
u.last_name = self.cleaned_data['last_name']
u.save()
#profile.save() #if commit=False in kwargs
return profile