簡體   English   中英

通過 django 中的視圖將 matplotlib 圖形渲染為 html

[英]Render matplotlib graph into html via views in django

我有一個 Django 視圖如下。 我正在使用 matplotlib 生成條形圖。

def myview(request, pk, sub):
    x=[1,2,3,4,5,6]
    y=[5,2,6,8,2,7]
    plot(x,y, linewidth=2)
    xlabel('x-axis')
    ylabel('yaxis')
    title('sample graph')
    grid(True)

    buffer = StringIO.StringIO()
    canvas = pylab.get_current_fig_manager().canvas
    canvas.draw()
    graphIMG = PIL.Image.fromstring("RGB", canvas.get_width_height(), canvas.tostring_rgb())
    graphIMG.save(buffer, "PNG")
    pylab.close()

    assgn = MyModel.objects.filter(data=pk, subject=sub)
    return render_to_response('mypage.html', {'assgn':assgn})

我如何在我的render_to_response傳遞條形圖和我的查詢? 另外我將如何在我的 html 中繪制這個圖?

您必須將繪圖保存為圖像文件,並將此文件的鏈接傳遞給您的模板。 我不熟悉您使用的庫,但我假設以下行會將圖形保存到實際的 png 文件中:

graphIMG.save(buffer, "PNG")

將其保存到磁盤后,您應該有一個文件路徑。 確保 Django 可以訪問此文件(即,將您的文件放在 settings.py 文件中 MEDIA_ROOT 指定的文件夾中)。

現在,將圖形的路徑傳遞給模板:

from django.shortcuts import render

def myview(request, pk, sub):
    ...
    imagepath = ...
    context = {'imagepath': imagepath}
    return render_to_response('mypage.html', context}

然后,在您的模板中:

<img src="{{ imagepath }}">

第一次嘗試時您可能不會得到它(即圖像未顯示)。 要調試它,請打開您的網頁並檢查指向您的圖像的鏈接,復制該鏈接並將其粘貼到您的瀏覽器中以查看您是否可以訪問它。 如果沒有,請檢查您的urls.py並添加以下行,以便 Django 提供圖像文件:

urlpatterns = patterns('',
    ...,

    url(r'^images/(.*)$', 'django.views.static.serve',
        {'document_root': settings.MEDIA_ROOT}), 
)

請注意 r'^images/(.*)$' 部分,您的設置可能與我的不同。

這是文檔: https : //docs.djangoproject.com/en/1.4/howto/static-files/

該文檔適用於 django 1.4(因此請單擊您使用的版本),但它也適用於更高版本的 django。 該文檔還提供了此解決方案的“快捷方式”版本。 所以閱讀它。

如文檔中所述,此解決方案僅適用於開發。 在生產中,您可能希望使用 apache 或 nginx 來提供靜態內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM