in my django
app,I have an index
page which lists some summary info which is dynamic(based on some user input data in db) . I have coded it as below
views.py
def custom_render(request,context,template):
req_context=RequestContext(request,context)
return render_to_response(template,req_context)
@login_required
def index(request, template_name):
summary_info = get_summary(...)
return custom_render(request,{'summary':summary_info},template_name)
urls.py
urlpatterns=patterns('',
...
url(r'^$', 'myapp.views.index',dict(template_name = 'myapp/index.html'), name = 'home'),
...
Now,I want to include a chart image generated by matplotlib on the home page..So,when user requests the index page url, he can see both the summary info and the chart
I have written the index.html as below
{% extends "myapp/base.html" %}
....
<div id='summary'>
{# here display the summary #}
...
</div>
<div id='chart'>
<img class="chartimage"src="{% url myapp_render_chart %}"
alt="chart"
/>
</div>
The chart view is
def render_chart(request):
data = get_data(request.user)
canvas = None
if data:
canvas = create_piechart(data)
response = HttpResponse(content_type = 'image/png')
if canvas:
canvas.print_png(response)
return response
import matplotlib.pyplot as plt
def create_piechart(data,chartsize=(16,16)):
...
figure = plt.figure(figsize = chartsize)
plt.pie(fracs, labels=labels, autopct='%1.1f%%', shadow=True)
canvas = FigureCanvas(figure)
plt.close(figure)
return canvas
I am not sure how I should do the urlmapping.The url r'^$',
is already mapped to the index page.But I need to create a url(...)
in urlpatterns
sothat the view render_chart() is associated with the name myapp_render_chart
and so can be called within {% url %}
tag . Can someone pls help me with this?
So you just want another url mapping? It wouldn't be very different from the one you already have. e.g.:
urlpatterns = patterns("myapp.views",
url(r'^$', 'index',dict(template_name = 'myapp/index.html'), name = 'home'),
url(r'^kick-ass-chart/$', 'render_chart', name='myapp_render_chart'),
)