繁体   English   中英

Django UpdateView通用类

[英]Django UpdateView generic class

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

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

<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.pk内部的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 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网站对于探索更新视图方法很有用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM