【问题标题】:Using matplotlib with Django Generic views将 matplotlib 与 Django 通用视图一起使用
【发布时间】:2013-08-22 12:12:20
【问题描述】:

我正在尝试为表中的每一行数据写一个详细的页面。我想使用每一行的数据为每一页动态生成一个 matplotlib 图。

我已经尝试了正常视图的代码,它可以工作。但是,当与detail_view 页面一起使用时,图像显示为断开的链接。我应该在 DetailView 类中包含什么来为每个页面生成图表?

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

我应该如何将图表链接到模板,最好不要使用静态或媒体标签?是否可以在不将 PNG 图像保存到静态文件夹的情况下生成图形?

【问题讨论】:

    标签: django matplotlib detailview


    【解决方案1】:

    有两种方法可以做到这一点,具体取决于您想要做什么。

      1234563方法并返回一个HttpResponse
    1. 如果你想显示一个嵌入了图像的 HTML 页面。然后你可以做两件事

      1. 创建一个单独的视图,该视图将仅响应您在示例中所做的图像,并在您的 HTML 页面中添加 &lt;img src="path to that view url" /&gt;

      2. 1234563 image。然后在您的模板中使用&lt;img src="data:image/png;base64,{{ image }}"/&gt; 创建一个带有base64 编码数据的图像标签。

    【讨论】:

    • 我发现 2.1 是最干净的方法
    【解决方案2】:

    这里有一个很好的例子。

    http://wiki.scipy.org/Cookbook/Matplotlib/Django

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-23
    • 2022-08-06
    • 2013-01-07
    • 1970-01-01
    • 2016-06-20
    • 2014-07-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多