Tuesday, 20 August 2013

Using matplotlib with Django Generic views

Using matplotlib with Django Generic views

I am trying to write a detailed page for each row of data in the table. I
would like to generate a matplotlib graph dynamically for each page using
the data from each row.
I have tried the code with a normal view and it works. However, when used
with the detail_view page the image appears as a broken link. What should
I include in the DetailView class to generate the graph for each page?
graph.py
def plotResults(request):
p=get_object_or_404(Read_alignment,pk=id)
x =[]
y=[]
x.append(p.start)
x.append(p.stop)
y.append(p.count)
y.append(p.count)
fig=plt.figure()
ax= fig.add_subplot(311)
ax.set_xlim(right=30)
ax.step(x,y,'-',where='post', label='post')
canvas = FigureCanvas(fig)
response= HttpResponse(mimetype='image/png')
canvas.print_png(response)
return response
url.py
url(r'^(?P<pk>\d+)/align/plotResults.png$',plotResults),
url(r'^(?P<pk>\d+)/align/$',AlignDetailView.as_view(),
name='AlignDetailView'),
views.py
class AlignDetailView(DetailView): model = Read_alignment
def get_queryset(self):
queryset= Read_alignment.objects.filter(chr__icontains=3l)
return queryset
def get_context_data(self, **kwargs):
context = super(AlignDetailView,self).get_context_data(**kwargs)
context['alignment'] = self.object
return context
Thanks for the help and pardon me as I have just picked up Django. How
should I link the graph to the template preferably without static or media
tags. Is it possible to generate the graphs without saving the png images
to the static folder?

No comments:

Post a Comment