我想获得的代码是一个页面,该页面具有一个简单的字段形式,可以使用UpdateView.
听起来很简单,但困难在于我希望 URL 映射url(r'email/(?P<pk>\d+)/$', EmailView.as_view(),)不id使用在我的 ModelForm ( User) 中使用的模型,而是使用id另一个模型 ( Profile) 的。
id特定用户实例的Profile可以在视图中按如下方式调用:self.user.get_profile().id. 如果您想知道,我正在使用Profile可重用应用程序userena的模型。
an 的一个(afaik 没有最佳实现¹)功能UpdateView是,如果您想使用自己的 ModelForm 而不是让UpdateView您需要从 Model 派生表单(否则会产生错误)定义model,queryset或get_queryset.
所以对于我的EmailView情况,我做了以下事情:
表格.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)
视图.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/。那是带有 with 的user电子邮件profile形式id 2。
如果我在里面运行一个调试器,EmailView我会得到这个:
>>> self.user.id
1
>>> profile = self.user.get_profile()
>>> profile.id
2
到目前为止,一切都很好。但是当我提交表单时,它不会保存。我可以覆盖 中的save方法,EmailModelForm但我宁愿覆盖我的EmailView. 我怎样才能做到这一点?
¹ 因为如果它是 ModelForm,则可以UpdateView从传递给属性的 ModelForm 派生模型类。form_class