我想得到的代码是一个页面,它有一个简单的字段形式,可以使用 UpdateView
更改用户的电子邮件地址。 .
听起来很简单,但难的是我想要 URL 映射 url(r'email/(?P<pk>\d+)/$', EmailView.as_view(),)
不使用 id
在我的 ModelForm 中使用的模型 ( User
) 但 id
另一个模型 ( Profile
)。 id
的 Profile
可以在 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
的电子邮件形式有一个 profile
与 id
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/