from django.template import RequestContext class PropertyBasedContext(RequestContext): """ This approach allows you to avoid code duplication to produce same context data for different views. It could be usefull when you are using templates inheritace. EXAMPLE: # views.py class CommonContext(PropertyBasedContext): def _get_common(self): return self.request.session.get('common') common = property(_get_common) class SomeContext(CommonContext): def _get_some(self): return "My first snippet" some = property(_get_some) class OtherContext(CommonContext): def _get_other(self): return MyModel.objects.all() other = property(_get_other) def some_view(request): return render_to_response('some_template.html', my_data_dictionary, context_instance=SomeContext(request)) def other_view(request): return render_to_response('other_template.html', my_data_dictionary, context_instance=OtherContext(request)) # base_template.html ... {{common}} ... # some_template.html {% extends "base_template.html" %} ... {{some}} ... # other_template.html {% extends "base_template.html" %} ... {{other}} ... """ def __init__(self, request, data=None, processors=None, current_app=None, use_l10n=None): RequestContext.__init__( self, request, data, processors, current_app, use_l10n) self.request = request classes, values = self.__base_classes(), { } for item in reversed(classes): for name, value in item.__dict__.items(): if type(value) is property: values[name] = value.fget(self) self.update(values) def __base_classes(self, current=None, classes=None): current, classes = current or self.__class__, classes or None classes.append(current) for base in current.__bases__: self.__base_classes(base, classes) return classes