deadlock
deadlock

Reputation: 7330

How can I display a pygooglechart in a Django view?

I'm currently playing around with pygooglechart. It's a python wrapper for Google charts.

In my views.py I have the following:

from pygooglechart import PieChart3D

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

In my urls.py I have linked up the view:

urlpatterns = patterns('',
    (r'^admin/', include(admin.site.urls)), 
    (r'^report/$', 'App.djangoapp.views.reporting'),
    (r'^facebook/', 'App.djangoapp.views.facebook'),
    (r'^twitter/', 'App.djangoapp.views.twitter'),
    (r'^pytest/', 'App.djangoapp.views.pytest'),

I know I need to put in a HttpResponse for my pytest view but I don't know how to render the image for the client who is accessing that url. When the client accesses that url, it should just generate an image of the graph. How can I go about doing this?

Upvotes: 1

Views: 840

Answers (1)

Abbasov Alexander
Abbasov Alexander

Reputation: 1938

You can use few approaches.

Example use redirect:

views.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())

Example use with template:

views.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)

template.html

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

Upvotes: 3

Related Questions