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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | 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
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 3 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Please login first before commenting.