Take the 2-minute tour ×

I have a django project (fairly simple) which uses the MPTT package, through it I create categories for specific models. I am creating a menu system which is based on the MPTT, but I find myself repeating my code in my views, to be more specific:

def index(request):
menu = MyCategory.objects.all()

def viewitem(request, item_slug):
menu = MyCategory.objects.all()

Should this be refactored to a template tag? should I make a helper function? Or create a middleware context which will pass the object to the template? Which would be the best implementation according to django logic? from the example its fairly simple that I return only a queryset to be used by the mptt existing tags:

{% if menu.exists %}
<nav id="topnavigation">
    {% spaceless %}
    {% recursetree menu %}
        <a href="{% url 'view-category' node.slug %}">{{ node.title }}</a>
        {% if not node.is_leaf_node %}
        <ul class="submenu">
            {{ children }}
        {% endif %}
    {% endrecursetree %}
    {% endspaceless %}
{% endif %}
share|improve this question

1 Answer 1

up vote 2 down vote accepted

The Django way is to use class-based views and create custom Mixin to contain repeated code. So the Mixin could look like this:

class MenuContextMixin(object):
    def get_context_data(self, **kwargs):
        context = super(MenuContextMixin, self).get_context_data(**kwargs)
        context['menu'] = MyCategory.objects.all()
        return context

And its usage would be like this:

class IndexView(MenuContextMixin, TemplateView):
    template_name = "index.html"

Since you are using function-based views, I think best solution would be to write a helper function to extend your context. E.g. views.py:

def get_extra_context():
    return {
        'menu': MyCategory.objects.all(),

def index(request):
    return render_to_response('index.html', context)
share|improve this answer
It's no problem for me to use Class based views, since I have used them in the past, I am using function based views only for the local dev thanks for the feedback :) –  petkostas Dec 30 '13 at 0:28
Thanks again :) refactored with mixins :) –  petkostas Dec 31 '13 at 1:31

Your Answer


