Heirarchy Trees from Objects.all() with Generic Views in Django

92 Views Asked by At

I'm working on a blog using Django. I'm using Generic Views ie.

from django.views.generic import dates 
from django.views.generic.list import ListView

These are working fine but I also wanted to implement a searchable, collapsable tree in the blog which covers all entries as another navigable tool. ie.

2016
  Dec
    01 - Entry 1
    03 - Entry 2
  Mar
    23 - Entry 3
2015
  Nov
    01 - Entry 4
etc.  

I'm currently doing this by using regroup and CSS inside an HTML template that I'm including into each HTML template used by each generic view:

  {% block sidebar %}
    {% include '../blog_archive_tree.html' %}
  {% endblock %}

My problem is that now I need to sub-class each generic view so that I can pass the queryset Objects.all() to the template to create the tree, which feels like I'm losing out on the benefits of using Generic classes.

From this in urls.py:

from django.views.generic.list import ListView
from coltrane.models import Category

urlpatterns = [ 
    url(r'^$', 
        ListView.as_view(model=Category),
]

to this:

from coltrane.models import Category
from coltrane.models import Entry


class ArticleCategoryListView(ListView):
    model = Category
    def get_context_data(self, **kwargs):
        context = super(ArticleCategoryListView, self).get_context_data(**kwargs)
        context['for_tree_view'] = Entry.objects.all()
        return context

urlpatterns = [
    url(
        r'^$',
        ArticleCategoryListView.as_view(),
        name='coltrane_category_list'),
    )

I've got about six generic views set up in this way and each one needs a sub-class. There has to be a better way of doing this? I've thought about pre-rendering the HMTL created by blog_archive_tree.html every time a change is made to the Blog but overwriting static files in a live environment on every change doesn't seem like a very stable approach to me.

Any insight/suggestions/alternatives would be well received.

NOTE - Update 2017.01.02 Following Daniel Roseman's comment I used an Inclusion Tag to achieve what was needed.

As the template had already been written this seems to be a neat way to do it.

In the application template tags (coltrane/templatetags/coltrane_tags.py) file I added the following:

from coltrane.models import Entry

@register.inclusion_tag('blog_archive_tree.html')
def entries_tree():
    entries = Entry.objects.all()
    return {'for_tree_view': entries}

The tag is called in a template:

{% load coltrane_tags %}
{% entries_tree  %}
0

There are 0 best solutions below