【问题标题】:Django UpdateView for Profile model that also includes a User form配置文件模型的 Django UpdateView,还包括一个用户表单
【发布时间】:2019-12-17 15:44:59
【问题描述】:

使用 Django 2.x,我有一个 Profile 模型,我想更新 Profile 的 UpdateView 中的一些 User 字段,例如 User.email

我可以显示电子邮件字段并显示当前值,但我不知道如何更新它。

这是我的设置:

models.py:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    # other fields

forms.py:

class UserForm(forms.ModelForm):
    class Meta:
        model=User
        fields=('email')

class ProfileForm(forms.ModelForm):
    class Meta:
        model=Profile
        fields=(...)

views.py

class ProfileUpdate(UpdateView):
    model=Profile
    form_class = ProfileForm
    user_form_class = UserForm


    def get_context_data(self, **kwargs):
        ...
        user = get_object_or_404(Profile, pk=self.kwargs.get('pk')).user

        context['user_form']= self.user_form_class(instance=user)

到目前为止,一切似乎都有效。用户表单有效并且当前的电子邮件地址出现在表单中。但是,这就是我卡住的地方,我不知道如何保存该电子邮件地址。

仍在 ProfileUpdate 中,这是我正在尝试的:

def post(self, request, *args, **kwargs):
    user_form = self.user_form_class(request.POST)
    if user_form.is_valid():
          user_form.save()
          # code makes it this far when submitting form.

    return super(ProfileUpdate, self).post(self, request, *args, **kwargs)

虽然代码运行了,但只有 Profile 模型被更新,User 模型没有得到更新的电子邮件地址。

【问题讨论】:

    标签: django django-class-based-views


    【解决方案1】:

    试试django-shapeshifterhttps://github.com/kennethlove/django-shapeshifter

    pip install django-shapeshifter

    自述文件中的示例完全符合您的要求。完全公开,我是该项目的贡献者。

    祝你好运!

    【讨论】:

    • 哇,太棒了,谢谢!您的项目可以与 django-crispy-forms 一起使用吗?
    • 我认为它应该能够,因为我相信django-crispy-forms 只是包装了常规的 Django 表单。试试看!
    猜你喜欢
    • 1970-01-01
    • 2021-05-29
    • 2020-07-03
    • 2011-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多