如何在Django视图中显示一个pygooglechart?

2024-10-02 12:34:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在玩pygooglechart。 这是一个用于Google图表的python包装器。在

在我的视图.py我有以下内容:

from pygooglechart import PieChart3D

def pytest(request):
     chart = PieChart3D(250, 100)
     chart.add_data([20, 10])
     chart.set_pie_labels(['Hello', 'World'])

在我的网址.py我把观点联系起来:

^{pr2}$

我知道我需要为pytest视图添加HttpResponse,但是我不知道如何为访问该url的客户机呈现图像。当客户端访问该url时,它应该只生成一个图形的图像。我该怎么做呢?在


Tags: frompy图像importadd视图urlpytest
1条回答
网友
1楼 · 发布于 2024-10-02 12:34:41

你可以用很少的方法。在

示例使用重定向:

视图.py

from django.http import HttpResponseRedirect
from pygooglechart import PieChart3D


def pytest(request):
    chart = PieChart3D(250, 100)
    chart.add_data([20, 10])
    chart.set_pie_labels(['Hello', 'World'])
    return HttpResponseRedirect(chart.get_url())

使用模板的示例:

视图.py

from django.template import RequestContext
from django.shortcuts import render_to_response
from pygooglechart import PieChart3D


def pytest(request):
    chart = PieChart3D(250, 100)
    chart.add_data([20, 10])
    chart.set_pie_labels(['Hello', 'World'])
    context = RequestContext(request, {
        'url_to_chart': chart.get_url()
    })
    template = 'path/to/template.html'
    return render_to_response(template, context)

模板.html

<img src="{{ url_to_chart }}" alt="" />

相关问题 更多 >

    热门问题