Django UpdateView 通用 class

Django UpdateView generic class

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

在模板中,当用户点击 link:

<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')

我想访问 class 中的 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')

我知道如何在基于 class 的普通函数中做到这一点,或者即使我从头开始重写基于 class 的视图,但我不想那样做。

class UpdatePeon(generic.UpdateView):
    if item['attr1'] == "Attribute1":
        model = model1
        form = model1Form
    else:
        ...

您不能像这样将代码放在 class 正文中。它在加载模块时运行,在您访问 request.

之前

您应该覆盖特定方法。例如,您可以覆盖 get_form_class 以更改视图使用的形式 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 很有用。