开发者

Django: Update related object on save?

I've "extended" Django's contrib.auth.models "user" like:

class UserProfile(models.Model):
   user = models.ForeignKey(User, related_name = 'profile')
   date_of_birth = models.DateField(blank=True, null=True)
   avatar = models.ImageField(upload_to=get_avatar_path, null=True, blank=True)
   friends = models.ManyToManyField(User, related_name = 'user_friends', blank=True, null=True)
   bio = models.TextField(null=True, blank=True)

I'd want the user to be able to update email from UserChangeForm, something like this:

forms.py

class UserUpdateForm(UserChangeForm):
   email = forms.EmailField()
   def __init__(self, *args, **kwargs):
      super(UserUpdateForm, self).__init__(*args, **kwargs)
      self.fields.pop('username')
      self.fields['email'].initial = self.instance.user.email

   class M开发者_如何学运维eta:
      exclude = ('friends', 'username', 'password1', 'password2')
      model = UserProfile

Except that one doesn't save the email.

I thought of trying to access request.post data from post_save signal so I could set user's new email there, but couldn't get that one working.

Any help is appreciated, thanks.


You need to override the form's save method as well:

class UserUpdateForm(UserChangeForm):
    email = forms.EmailField()

    class Meta:
        exclude = ('friends', 'username', 'password1', 'password2')
        model = UserProfile

    def __init__(self, *args, **kwargs):
        super(UserUpdateForm, self).__init__(*args, **kwargs)
        self.fields.pop('username')
        self.fields['email'].initial = self.instance.user.email

    def save(self, commit=True):
        self.instance.user.email = self.cleaned_data['email']
        if commit:
            self.instance.user.save()
        super(UserUpdateForm, self).save(commit) 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜