About Generating Favicons on the Fly

Create favicons dynamically using the Pillow library as follows:

from io import BytesIO
from PIL import Image, ImageDraw
from django.http import HttpResponse

def create_favicon(request):
    # Create a blank image with an alpha channel
    image = Image.new("RGBA", (100, 100), (255, 255, 255, 0))

    outer_radius = 25
    inner_radius = 15
    center_x = 50
    center_y = 50
    draw = ImageDraw.Draw(image)
    draw.ellipse(
        (
            center_x - outer_radius,
            center_y - outer_radius,
            center_x + outer_radius,
            center_y + outer_radius,
        ),
        fill="#215a00",
    )
    draw.ellipse(
        (
            center_x - inner_radius,
            center_y - inner_radius,
            center_x + inner_radius,
            center_y + inner_radius,
        ),
        fill="#fff",
    )

    # Generate the different sizes of the favicon
    sizes = [(16, 16), (32, 32), (48, 48)]
    images = []
    for size in sizes:
        image_version = image.resize(size, resample=Image.BICUBIC)
        images.append(image_version)

    # Create a BytesIO object to hold the ICO file
    buffer = BytesIO()
    images[0].save(buffer, "ICO", sizes=[(s[0], s[1]) for s in sizes])
    buffer.seek(0)

    # Create an HttpResponse object with the ICO file
    response = HttpResponse(buffer.read(), content_type="image/x-icon")
    response["Content-Disposition"] = "inline; filename=favicon.ico"

    return response

Then you can set the favicon for your website with this URL rule:

from django.urls import path
from favicon.views import favicon_view

urlpatterns = [
    path("favicon.ico", create_favicon, name="favicon"),
]

Tips and Tricks Programming Django 4.2 Django 3.2 Django 2.2 Python 3 Pillow Favicon