简体   繁体   English

Django UpdateView通用类

[英]Django UpdateView generic class

How can I access the object passed by the user inside a generic view class? 如何在通用视图类中访问用户传递的对象?

In template, when the user clicks the link: 在模板中,当用户单击链接时:

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

this goes to urls.py: 转到urls.py:

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

and my view: 和我的看法:

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

I would like to access the item.attr1 or at least item.pk inside the class so I could change the model and form accordingly, something like: 我想访问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')

I know how to do it in a normal function based class or even if I rewrite a class based view from scratch but I don't want to do that. 我知道如何在基于普通函数的类中做到这一点,即使我从头开始重写基于类的视图,但我也不想这样做。

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

You can't put code in the class body like this. 您不能像这样将代码放入类主体中。 It runs when the module is loaded, before you have access to the request . 它会在模块加载时运行,然后才能访问request

You should override a specific method. 您应该覆盖特定的方法。 For example you can override get_form_class to change the form class used by the view. 例如,您可以重写get_form_class来更改视图使用的表单类。 Inside the view, you can access the object being updated with self.object . 在视图内部,您可以访问使用self.object更新的对象。

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

You may find the ccbv website useful for exploring the update view methods . 您可能会发现ccbv网站对于探索更新视图方法很有用。

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

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