About SVG Graphs

Draw SVG graphs with the pygal library, as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import pygal
from django.http import HttpResponse
from .models import PageStats

def total_visits_svg(request):
    chart = pygal.Pie(inner_radius=0.4)
    chart.title = gettext("Visits")
    for stats in PageStats.objects.all():
        chart.add(stats.page_title, stats.get_visit_count())
    svg = chart.render(is_unicode=True)
    return HttpResponse(svg, content_type="image/svg+xml")

Then if you include the SVG as an embed tag, you get an interactive graph. If you include it to HTML as an image, it's static.

1
2
{% url "total_visits_svg" as svg_url %}
<embed src="{{ svg_url }}" />

Tips and Tricks Programming Web Design Django 4.x Django 3.2 Django 2.2 Python 3 JavaScript SVG