django:将额外的参数传递给具有通用视图类的模板

问题描述:

我想使用相同的模板来显示django中不同模型的记录,并使用泛型类查看器。泛型类观察器已经接受了模板中所需的大部分参数,除了一个。django:将额外的参数传递给具有通用视图类的模板

如何将上下文中的这个额外参数传递给模板?

我试图把它当作URL配置第三(额外)的说法,都没有成功:

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

url(r'^software/(?P<pk>[\w-]+)/$', 
    UpdateView.as_view(
     model=Software, 
     template_name='model_form.html', 
     success_url=reverse_lazy('software-list'), 
     ), 
    {'extrainfo': "Software"}, 
    name='software-detail' 
), 

将会有几个类似的URLconf这些在我的应用程序。

一种可能性是对视图类进行子分类并提供我自己的get_context_data方法实现,该方法添加所需的键值对。

但是这个解决方案太重复了,因为它会应用到视图类的每一次使用。

也许有可能只做视图类的一个子类。这个新类中的as_view类方法将接受一个新的命名参数,该参数将在重新定义get_context_data时进入上下文。

我对django和Python没有太多的经验,所以我不知道如何做到这一点,我接受的帮助。

我想你只能使用UpdateView的一个子类来完成此操作,而不是我认为您需要的每个模型。

参数来as_view被置为被返回的对象的属性,所以我觉得你可以做

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 

然后再调用这个在URLconf像

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

我不是可以肯定的是,你应该这样做 - 它正朝着urls.py中的太多东西前进。

+0

我来到了一个类似的解决方案,它的工作原理。我还编写了一个函数,用于获取模型类(示例中为“Processor”)和字符串(示例中为“processor”),并返回类似于上例中给出的urlconf。有了这个功能,我可以轻松地为我的应用程序的大多数数据模型构建urlconf。 – Romildo 2012-08-04 03:25:14

+0

这已经过时了。现在你可以做'def yourinfo(self):在你的CBV中返回'yourvalue',它可以作为一个名为'view.yourinfo'的模板变量自动提供! – 2017-05-03 04:16:28

我已经通过继承通用视图,这样做:

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

而且在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 

事实上,我总是创造我自己的子类,即使不需要任何额外的功能;这样我就有了更多的控制权,并且视图和url配置清晰分离。