Using template tags would probably be the route I would take here. I've had a similar situation to this, whereby I had calendar information being rendered multiple times in different formats on the same page. The way I handled it was by passing the queried data into the request context, then simply using that queryset as an argument of a template tag. The result is that you can end up with template syntax like this:
View
def my_view(request, *args, **kwargs):
yearly_sales_qs = SaleRecord.objects.filter(param=value)
monthly_sales_qs = SalesRecord.objects.filter(param=foo)
return render_to_response( ..., locals(), ... )
Template
{% load data_tags %}
<div class="year">
{% render_data_table for yearly_sales_qs %}
{% render_bar_chart for yearly_sales_qs %}
</div>
<div class="month">
{% render_data_table for monthly_sales_qs %}
{% render_bar_chart for monthly_sales_qs %}
</div>
So how do you make something like that? Start by checking out the Django doc on Custom template tags and filters. It's a little more difficult to get started than the rest of Django, but once you get it, it's pretty easy.
- Start by creating a folder "templatetags" in your app's folder.
- Make a blank file "init.py" in that new folder
- Add the location of that templatetags folder to the
TEMPLATE_DIRS
setting in settings.py
(if it's not already there)
Because we'll be making several of these, we can make a base template tag that we'll inherit off of that encapsulates our basic functionality...
data_tags.py (stored inside of templatetags
folder)
class DataForTag(tempalte.Node):
@classmethod
def handle_token(cls, parser, token, template):
tokens = token.contents.split()
if tokens[1] != 'for':
raise template.TemplateSyntaxError("First argument in %r must be 'for'" % tokens[0])
if len(tokens) == 3:
return cls(queryset=parser.compile_filter(tokens[2]), template=template)
else:
raise template.TemplateSyntaxError("%r tag requires 2 arguments" % tokens[0])
def __init__(self, queryset=None, template=None):
self.queryset = queryset
self.template = template
def render(self, context):
return render_to_string(self.template, {'queryset':self.queryset})
Then we can make individual tags that handle whatever we need them to...
@register.tag
def render_bar_chart(parser, token):
return DataForTag.handle_token(parser, token, 'data/charts/barchart.html')
@register.tag
def render_pie_chart(parser, token):
return DataForTag.handle_token(parser, token, 'data/charts/piechart.html')
@register.tag
def render_data_table(parser, token):
return DataForTag.handle_token(parser, token, 'data/table.html')