【问题标题】:'UpdateView with a ModelForm as form_class'-issue'UpdateView with a ModelForm as form_class'-issue
【发布时间】:2013-07-14 16:53:05
【问题描述】:

我想获得的代码是一个页面,该页面具有一个简单的字段形式,用于使用UpdateView 更改用户的电子邮件地址。

听起来很简单,但困难在于 我希望 URL 映射 url(r'email/(?P<pk>\d+)/$', EmailView.as_view(),) 不使用我的 ModelForm 中使用的模型的 id (User),而是使用另一个模型的 id ( Profile)。

特定用户的Profile 实例的id 可以在视图中按如下方式调用:self.user.get_profile().id。如果您想知道,我正在使用可重用应用程序userenaProfile 模型。

UpdateView 的一个(afaik 未最佳实现¹)功能是if you want to use your own ModelForm instead of letting the UpdateView derive a form from a Model you need to(otherwise produces an Error) define either model, queryset or get_queryset

所以对于我的EmailView 案例,我做了以下操作:

forms.py

class EmailModelForm(forms.ModelForm):
    class Meta:
        model = User
        fields = (
          "email",
        )

    def save(self, *args, **kwargs):
        print self.instance
        # returns <Profile: Billy Bob's Profile> instead of <User: Billy Bob> !!!
        return super(EmailModelForm, self).save(*args, **kwargs)

views.py

class EmailView(UpdateView):
    model = Profile # Note that this is not the Model used in EmailModelForm!
    form_class = EmailModelForm
    template_name = 'email.html'
    success_url = '/succes/'

然后我去了/email/2/。那是user 的电子邮件形式,它有一个profileid 2

如果我要在 EmailView 中运行调试器,我会得到:

>>> self.user.id
1

>>> profile = self.user.get_profile()
>>> profile.id
2

到目前为止一切顺利。但是当我提交表单时它不会保存。我可以覆盖EmailModelForm 中的save 方法,但我宁愿覆盖EmailView 中的某些内容。我该怎么做?

¹ 因为 UpdateView 可以从传递给 form_class 属性的 ModelForm 派生模型类,以防它是 ModelForm。

【问题讨论】:

    标签: django django-class-based-views django-forms


    【解决方案1】:

    让你的视图和模型形式对应于不同的模型对我来说似乎是个坏主意。

    我会在您的EmailView 中设置model = User,然后覆盖get_object,以便它返回与给定配置文件ID 对应的用户。

    【讨论】:

    • 确实,非常感谢。当我使用get_object 时,我什至不需要设置model 属性
    猜你喜欢
    • 2022-12-27
    • 1970-01-01
    • 2022-12-01
    • 2022-12-27
    • 2022-12-19
    • 2022-11-20
    • 2021-03-05
    • 2021-04-12
    • 2014-05-10
    相关资源
    最近更新 更多