在 Django 模板上渲染 Python seaborn 图

Render Python seaborn Plot on Django Template

我正在尝试在 Django 模板上渲染 seaborn 生成的绘图。

我的 views.py 中有以下代码:

def booking_hour_plot():
    qs = bookings_today()
    df = read_frame(qs)
    plot = sns.countplot(data=df)
    return plot

def render_stats_page(request):
    #general info
    user_count = total_users_until_now()
    cancel_rate = activity_cancel_rate()

    #activity/booking details
    activity_set = activities_today()
    booking_set = bookings_today()
    plot = booking_hour_plot()

    return render(request, "stats.html", {'name':'Avonmore Statistics', 

    'total_user':int(user_count),
    'cancel_rate': round(float(cancel_rate), 2),
    'booking_count_today': booking_set.count(),
    'activity_count_today': activity_set.count(),

    'activities_today': activity_set,
    'bookings_today': booking_set,
    'booking_hour_plot': plot,
    
    })

我有一个名为 stats.html 的 html 模板,其中包含情节。 templates目录和views.py在同一个目录:

<li>Real Time Plot: {{booking_hour_plot}}</li>

但是,呈现的 html 页面并没有真正显示情节。它更像是情节对象: enter image description here

知道如何将真实情节而不是这个情节对象放在 html 页面上吗?

尝试将您的 plot 保存并编码为 png 文件,然后显示为 <img> 元素 tag这样:

from io import BytesIO
import base64

def booking_hour_plot():
    qs = bookings_today()
    df = read_frame(qs)
    plot = sns.countplot(data=df)
    plot_file = BytesIO() 
    plot.savefig(plot_file, format='png')
    encoded_file - base64.b64encode(plot_file.getValue())
    return encoded_file

stats.html中:

<li>Real Time Plot: <img src='data:image/png;base64,{{booking_hour_plot}}'/></li>