django: passing extra argument to the template with generic view class

谁说胖子不能爱 提交于 2019-12-06 09:46:47

I think you can do this with only one subclass of UpdateView, rather than the one per model that I think you think you need.

Arguments to as_view get set as attributes on the object which is returned, so I think you could do

class MyUpdateView(UpdateView):
    extrainfo = None

    def get_context_data(self, **kwargs):
        context = super(MyUpdateView, self).get_context_data(self, **kwargs)
        context['extrainfo'] = self.extrainfo

        return context

And then call this in your urlconf like

url(r'^processador/(?P<pk>[\w-]+)/$',
    MyUpdateView.as_view(
        model=Processador,
        template_name='model_form.html',
        success_url=reverse_lazy('processador-list'),
        extrainfo="Processador"
        ),
    name='processador-detail'
)

I'm not at all sure you should do this though - it's heading towards too much stuff in the urls.py.

I've been doing it by subclassing the generic view, like this:

In urls.py:

url(r'^processador/(?P<pk>[\w-]+)/$', ProcessadorUpdateView.as_view(), name='processador-detail'),
url(r'^software/(?P<pk>[\w-]+)/$', SoftwareUpdateView.as_view(), name='software-detail'),

And in views.py:

class ProcessadorUpdateView(UpdateView):
    model=Processador
    template_name='model_form.html'
    success_url=reverse_lazy('processador-list') # I'm not sure this will work; I've used get_success_url method
    def get_context_data(self, **context):
        context[self.context_object_name] = self.object
        context["extrainfo"] = "Processador"
        return context

In fact, I always create my own subclasses, even if there is no need for any extra functionality; this way I have more control and the views and urlconfigs are clearly separated.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!