Django:保存时更新相关对象?

时间:2011-04-16 16:27:28

标签: django django-forms

我已经“扩展”了Django的contrib.auth.models“用户”,如:

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)

我希望用户能够从UserChangeForm更新电子邮件,如下所示:

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 Meta:
      exclude = ('friends', 'username', 'password1', 'password2')
      model = UserProfile

除了不保存电子邮件之外。

我想过尝试从post_save信号中访问request.post数据,这样我就可以在那里设置用户的新电子邮件,但无法使用那个。

感谢任何帮助,谢谢。

1 个答案:

答案 0 :(得分:1)

您还需要覆盖表单的save方法:

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)