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

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

我想得到的代码是一个页面,它有一个简单的字段形式,可以使用 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/

相关文章:

Django - 根据模板中用户定义的顺序对对象进行排序

Django FormView 与 CreateView

python - django.db.utils.IntegrityError : (1062, "Duplicate entry ' ' 键 'slug' ")

python - Django 分页泛型 LISTCREATEAPIview 中的条件查询集

django - 在 Django Formset 中过滤对象

Django UpdateView 不加载带有样式的表单

django - 如何在 Django 中将 http 请求从 Post 更改为 Get?

python - 基于类的 View 中的可选 url 参数

django - 在 Django Forms 中访问 request.GET 或 request.POST

python - ImageField() 不在 ModelForm 中保存图像 - Django/Python