gpt4 book ai didi

django - 'UpdateView with a ModelForm as form_class'-issue

转载 作者:行者123 更新时间:2023-12-01 02:24:33 25 4
gpt4 key购买 nike

我想得到的代码是一个页面,它有一个简单的字段形式,可以使用 UpdateView 更改用户的电子邮件地址。 .

听起来很简单,但难的是我想要 URL 映射 url(r'email/(?P<pk>\d+)/$', EmailView.as_view(),)不使用 id在我的 ModelForm 中使用的模型 ( User ) 但 id另一个模型 ( Profile )。
idProfile可以在 View 中按如下方式调用特定用户的实例:self.user.get_profile().id .我正在使用 Profile可重用应用程序模型 userena如果你想知道。
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)

View .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

到现在为止还挺好。但是 当我提交表单时,它不会保存。我可以覆盖 save EmailModelForm 中的方法但我宁愿覆盖我的 EmailView 中的某些内容.我怎样才能做到这一点?

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

最佳答案

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

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

关于django - 'UpdateView with a ModelForm as form_class'-issue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17677721/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com