【问题标题】:Django UpdateView generic classDjango UpdateView 泛型类
【发布时间】:2018-11-03 09:24:17
【问题描述】:

如何在通用视图类中访问用户传递的对象?

在模板中,当用户点击链接时:

<td><a href="{% url 'update_peon' pk=item.pk %}"><button class="btn btn-warning">Edit</button></a></td>

这转到 urls.py:

url(r'^update_peon/(?P<pk>\d+)$', views.UpdatePeon.as_view(), name='update_peon'),

我的看法:

   class UpdatePeon(generic.UpdateView):

        login_required = True
        template_name = 'appform/Peons/peon_form.html'
        model = Person
        form_class = PersonForm
        success_url = reverse_lazy('view_peons')

我想访问类中的item.attr1 或至少item.pk,这样我就可以相应地更改模型和形式,例如:

   class UpdatePeon(generic.UpdateView):

        login_required = True
        template_name = 'appform/Peons/peon_form.html'

        if item['attr1'] == "Attribute1":
            model = model1
            form = model1Form
        else:
             etc

        success_url = reverse_lazy('view_peons')

我知道如何在基于普通函数的类中执行此操作,或者即使我从头开始重写基于类的视图,但我不想这样做。

【问题讨论】:

  • 不清楚为什么要更改model 之后你有项目。 model 用于获取项目。
  • @Alasdair 好吧,我需要更改模型,因为:假设我有一个 Parent 模型,其名称和类别作为字段。对于每个category,我都有一个子模型。用户点击edit,我需要为他显示适当的child form,因为所有子表单都显示在同一个视图中。
  • 听起来你需要覆盖get_object。拥有物品后设置self.model 没有意义,因为之后不再使用self.model

标签: python django django-views django-class-based-views


【解决方案1】:
class UpdatePeon(generic.UpdateView):
    if item['attr1'] == "Attribute1":
        model = model1
        form = model1Form
    else:
        ...

您不能像这样将代码放在类主体中。它在模块加载时运行,在您访问 request 之前。

你应该重写一个特定的方法。例如,您可以覆盖get_form_class 以更改视图使用的表单类。在视图内部,您可以使用self.object 访问正在更新的对象。

class UpdatePeon(generic.UpdateView):
    def get_form_class(self):
        if self.object.pk == 1:
            return MyForm
        else:
            return OtherForm

您可能会发现 ccbv 网站对探索 update view methods 很有用。

【讨论】:

  • 感谢您的回复!对于 model 对象,我应该使用 get_object 吗?我需要动态更改modelform
  • 您的建议效果很好,但我还需要根据self.object.pk 设置model。现在我只能选择form_class
  • model 仅用于获取对象。一旦调用了self.get_object(),就没有必要更改self.model。覆盖get_object 可能有效。调用self.object = super(UpdatePeon, self).get_object() 获取父模型,然后用它把self.object 替换为正确模型的实例。
猜你喜欢
  • 2021-05-29
  • 2014-12-03
  • 2017-01-02
  • 1970-01-01
  • 2012-03-05
  • 2021-10-18
  • 2019-05-30
  • 1970-01-01
  • 2011-09-05
相关资源
最近更新 更多