Skip to content

Instantly share code, notes, and snippets.

@hdformat
Created January 18, 2026 14:46
Show Gist options
  • Select an option

  • Save hdformat/a965046f79e23951cdec5934a1ff7b66 to your computer and use it in GitHub Desktop.

Select an option

Save hdformat/a965046f79e23951cdec5934a1ff7b66 to your computer and use it in GitHub Desktop.
Server-Sent Event (SSE) Django & HTMX

Server-Sent Event (SSE) Django & HTMX

views.py

def stream_view(request):
    def event_stream():
        while True:
            rv = ""
            event_data = {
                "event": "clock",
                "data": f"The server time is {time.strftime('%Y-%m-%d %H:%M:%S')}",
            }
            for k, v in event_data.items():
                rv += f"{k}: {v}\n"
            rv += "\n"
            yield rv
            time.sleep(1)
    return StreamingHttpResponse(event_stream(), content_type="text/event-stream")

index.html

<!doctype html>
<html lang="en">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <meta name="robots" content="NONE,NOARCHIVE" />
    <title>🥑</title>
    <script src="https://cdn.jsdelivr.net/npm/htmx.org@2.0.8/dist/htmx.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/htmx-ext-sse@2.2.4"></script>
  </head>
  <body>
    <div hx-ext="sse" sse-connect="/stream">
      <div sse-swap="clock" hx-swap="innerHTML">🕑</div>
    </div>
  </body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment