django - 允许使用 django-profiles 更改用户字段(如电子邮件)

标签 django django-models django-forms

Django 允许您创建一个外键为 User 的模型,并在设置中将其定义为官方“配置文件”模型,其中包含用户帐户的附加数据。 django-profiles让您轻松显示/创建/编辑该配置文件数据。但用户的主要电子邮件地址是其主帐户的一部分,而不是其扩展配置文件的一部分。因此,当你把

{{ form }}

在 profile/edit_profile 模板中,主电子邮件地址不显示。您可以手动检索它
{{ user.email }}

但是在提交时,对它的更改不会保存回帐户。我假设已经创建了一个自定义 ModelForm,例如:
class ProfileForm(ModelForm):

  class Meta:
      model = Parent
      exclude = ('family','user','board_pos','comm_job',)

并且 ProfileForm 正在通过 urlconf 传递给 django-profiles 的 View 代码,例如:
('^profiles/edit', 'profiles.views.edit_profile', {'form_class': ProfileForm,}),

如果您想让用户更改他们的名字或姓氏,也会出现同样的问题。在使用 django-profiles 时,让用户更改自己的电子邮件地址或姓名的最佳方法是什么?

最佳答案

这是我们最终使用的解决方案:

# urls.py
    # First match /profiles/edit before django-profiles gets it so we can pass in our custom form object.
    ('^profiles/edit', 'profiles.views.edit_profile', {'form_class': ProfileForm,}),
    (r'^profiles/', include('profiles.urls')),

现在我们重写表单本身的save方法,这样当表单被保存时,电子邮件地址同时被推送到保存用户的User对象中。优美。
# forms.py , trimmed for brevity

class ProfileForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(ProfileForm, self).__init__(*args, **kwargs)
        try:
            self.fields['email'].initial = self.instance.user.email
        except User.DoesNotExist:
            pass

    email = forms.EmailField(label="Primary email")

    class Meta:
      model = Parent

    def save(self, *args, **kwargs):
      """
      Update the primary email address on the related User object as well. 
      """
      u = self.instance.user
      u.email = self.cleaned_data['email']
      u.save()
      profile = super(ProfileForm, self).save(*args,**kwargs)
      return profile

完美运行。感谢 mandric .

关于django - 允许使用 django-profiles 更改用户字段(如电子邮件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1075314/

相关文章:

python - Django 正确使用 Models.Cascade (on_delete)

python - django 1.8 中的 ImageField 类不在模板中显示图像

python - 以 Django 形式获取请求数据

python - 使用 Django 和 python 迁移模型时出现错误

python - AttributeError at/'tuple' 对象没有属性 '_meta'

python - 无效的 Django 表单

python - Django 表单在创建用户时不保存密码

django 管理员在内联覆盖保存方法?

python - 如何在 drf_yasg 中将方案从 HTTP 更改为 HTTPS?

python - 在基于类的 View 中使用@transaction.atomic 保存模型