About Image Data URLs

The <img> tags support data URLs as sources:

<img src="data:..." alt="" />

This allows you to dynamically generate SVG images for avatars or other purposes and display them directly in your templates. Here’s an example of how to create such a data URL:

def get_avatar_url(initials="DT", bg_color="#215a00"):
    import base64

    svg = f"""<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100">
        <rect width="100" height="100" fill="{bg_color}"/>
        <text x="50" y="50" font-family="Arial, sans-serif" font-size="40" font-weight="bold" fill="white" text-anchor="middle" dominant-baseline="central">{initials}</text>
    </svg>"""

    svg_base64 = base64.b64encode(svg.encode("utf-8")).decode("utf-8")
    return f"data:image/svg+xml;base64,{svg_base64}"

Tips and Tricks Programming Development Django 5.2 Django 4.2 Python 3 HTML5 SVG