Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Class Based View Composite

I'm using Django 1.3's Class-base generic views for a project. They're really nice but I would like to be DRYer. I have a page that displays a list of press coverage we've received and another which displays a list of articles we've published. On the overview page I need to display both lists. I would like to create a composite view which accepts both views and creates a context with both querysets attached.

like image 331
Kenzic Avatar asked Apr 21 '11 22:04

Kenzic


1 Answers

Kenzic was able to accomplish this by doing the following:

composite.py:

from django.views.generic.base import TemplateResponseMixin, View

class BaseCompositeView(TemplateResponseMixin, View):

    composite_views = []

    def get_composite_views(self):
        return self.composite_views

    def get_context_data(self, request, *args, **kwargs):
        context = {}
        composite_views = self.get_composite_views()
        for composite_view in composite_views:
            cls = composite_view[0]
            try:
                clsview = cls.as_view(**composite_view[1])
            except IndexError:
                clsview = cls.as_view()

            view = clsview(request, *args, **kwargs)
            context_data = view.context_data
            context.update(context_data)

        return context

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(request, *args, **kwargs)
        return self.render_to_response(context)

views.py:

from django.views.generic import TemplateView, ListView, DetailView
from composite import BaseCompositeView
from .models import *


class MediaCoverageList(ListView):
    queryset = MediaCoverageItem.objects.order_by('-date')


class PressKitList(ListView):
    queryset = PressKit.objects.all()


class NewsroomLanding(BaseCompositeView):
    template_name = 'newsroom/landing.html'
    composite_views = [
        (MediaCoverageList,{
            'paginate_by': 10,
        },),
        (PressKitList,)

    ]
like image 139
akaihola Avatar answered Sep 20 '22 11:09

akaihola