将多个视图传递给模板

时间:2013-01-23 14:44:23

标签: django django-models django-templates django-views django-class-based-views

我有一个页面应该显示事件和此事件的演示文稿。在我的代码中,它们没有关系(我仍然需要解决这个问题)。在接收事件和讲座的主页上,视图如下:

views.py

class EventoView(ListView):
    model = Evento
    template_name = 'home.html'
    context_object_name = 'evento_list'
    queryset = Evento.objects.all().order_by('-data')[:1]

class RegistroView(ListView):
    model = Registro
    template_name = 'home.html'
    context_object_name = 'registro_list'
    queryset = Registro.objects.all()

问题在于我只能传递Event对象,即注册对象,其中显示的索引也必须传递,但是,只接受URL的Django视图。

urls.py

urlpatterns = patterns('',
    url(r'^$', EventoView.as_view(), name='home'), #I can't pass two views
    url(r'^cadastro/', CriarRegistroView.as_view(), name='cadastro'),
    url(r'^contato/', CriarContatoView.as_view(), name='contato'),
    url(r'^sobre/', SobreView.as_view(), name='sobre'),
    url(r'^admin/', include(admin.site.urls)),
)

我该如何解决这个问题?

感谢。

1 个答案:

答案 0 :(得分:3)

看起来你可以override ListView.get_context_data

class RegistroView(ListView):

    model = Evento

    def get_context_data(self, **kwargs):
        context = super(RegistroListView, self).get_context_data(**kwargs)
        context['registros'] = Registro.objects.all()
        context['eventos'] = Evento.objects.all().order_by('-data')[:1]            
        return context

我没有使用ListViews的经验所以我不知道我是否正在使用它,因为它应该被使用,或者不是

相关问题