【问题标题】:Render Python seaborn Plot on Django Template在 Django 模板上渲染 Python seaborn Plot
【发布时间】:2021-11-21 19:58:46
【问题描述】:

我正在尝试在 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 模板,其中包含该图。模板目录和views.py在同一个目录:

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

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

任何想法如何将真正的情节放在 html 页面上,而不是这个情节对象?

【问题讨论】:

    标签: python django seaborn


    【解决方案1】:

     尝试将您的 plot 保存并编码为 png 文件,然后以这种方式显示为 &lt;img&gt; 元素 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>
    

    【讨论】:

      猜你喜欢
      • 2022-07-22
      • 2017-08-06
      • 2018-05-20
      • 2018-11-05
      • 2016-06-07
      • 2013-10-10
      • 2012-03-18
      • 2017-05-25
      • 2015-09-17
      相关资源
      最近更新 更多