2👍
✅
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):
...
context.update(get_extra_context())
return render_to_response('index.html', context)
Source:stackexchange.com