About Generating SVG Images on the Fly

You can create SVG images in Django views on the fly using the svgwrite package, as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
from django.http import HttpResponse
import svgwrite

def create_svg(request):
    drawing = svgwrite.Drawing(
        size=("100%", "100%"), profile="tiny"
    )
    drawing.add(
        drawing.circle(
            center=("50%", "50%"), r="20%", fill="#215a00"
        )
    )
    drawing.add(
        drawing.circle(
            center=("50%", "50%"), r="10%", fill="#fff"
        )
    )
    svg_data = drawing.tostring()
    return HttpResponse(svg_data, content_type="image/svg+xml")

Tips and Tricks Programming Django 4.2 Django 3.2 Django 2.2 Python 3 SVG svgwrite