【发布时间】: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。如果您想知道,我正在使用可重用应用程序userena 的Profile 模型。
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 的电子邮件形式,它有一个profile 和id 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