Django's built-in django.views.generic.TemplateView is a powerful tool.
It includes all the methods needed to generate HTML, making it very easy to create pages.
Although simple, it is rich in features and flexible, allowing for various ways to write code.
・Override the get method
def get(self, request, **kwargs): return self.render_to_response({ 'items': Hoge.objects.filter(...) })
・Inject variables from urls.py
url(r'^page/$', TemplateView.as_view( template_name="html_page/agreement.html", items=xxx), name='page'),
This time, I will show an example of sending variables to the template using cached_property.
Looking at the get method of TemplateView,
context = self.get_context_data(**kwargs)
there is such code. And, looking at get_context_data,
def get_context_data(self, **kwargs): if 'view' not in kwargs: kwargs['view'] = self return kwargs
it looks like this.
In other words, if you do not override TemplateView's get and get_context_data, you can access the calling view instance from within the template using the view argument.
Therefore,
class HogeView(TemplateView): template_name = '........' @cached_property def items(self): return list(Hoge.objects.filter(...)) @cached_property def total(self): return sum([ i.count for i in self.items]) @cached_property def average(self): return self.total / len(self.items)
Template
<table> {% for item in view.items %} <tr> .... {{ item.... }} </tr> {% endfor %} </table> Total: {{ view.total }} Average: {{ view.average }}
This kind of approach is also valid. It allows for separation of concerns and reduces the number of SQL queries issued.
However, there is a drawback that exceptions may be swallowed when they occur.
Comments