← Back to Blog

Django + Svelte: async Python backend, reactive Svelte stores

·9 min read

Django + Svelte pairs Django's mature ecosystem with Svelte's reactive store model. The wiring is the same as every other Django example, import views in urls.py, and call mount_django(urlpatterns). The Svelte side uses createSvelteClient and the $store subscription pattern.

Server

# views.py
@rpc.query
async def greet(name: str = "World") -> dict:
    return {"message": f"Hello, {name}!", "framework": "Django"}

@rpc.query
async def read_item(item_id: int, q: str = None) -> dict:
    return {"item_id": item_id, "q": q}

@rpc.mutation
async def create_item(name: str, description: str = None) -> dict:
    return {"name": name, "description": description, "created": True}

# urls.py
from . import views  # triggers registration
from pyrpc_django import mount_django
urlpatterns = [...]
mount_django(urlpatterns)

# settings.py
CORS_ALLOWED_ORIGINS = ["http://localhost:5173"]

Client

// src/lib/pyrpc.ts
import { createSvelteClient } from "@pyrpc/svelte"
import type { Types } from "@pyrpc/types"

export const api = createSvelteClient<Types>({
  baseUrl: import.meta.env.VITE_API_URL ?? "http://localhost:8000",
})
<!-- src/routes/+page.svelte -->
<script lang="ts">
  import { api } from "$lib/pyrpc"
  let name = ""
  const greeting = api.greet.createQuery(() => ({ name: "Django User" }))
  const item = api.read_item.createQuery(() => ({ item_id: 42, q: "django-test" }))
  const createItem = api.create_item.createMutation()
  function handleCreate() {
    $createItem.mutate({ name }); name = ""
  }
</script>

{#if $greeting.isPending}<p>Loading…</p>
{:else}<pre>{JSON.stringify($greeting.data)}</pre>{/if}
<pre>{JSON.stringify($item.data)}</pre>
<input bind:value={name} />
<button on:click={handleCreate} disabled={$createItem.isPending}>
  {$createItem.isPending ? "Creating…" : "Create"}
</button>
{#if $createItem.isSuccess}<pre>{JSON.stringify($createItem.data)}</pre>{/if}

Run it

cd server && uv add pyrpc-core[django] && pyrpc dev --yes --module myproject.views
cd client && npm install && npm run dev

Open http://localhost:5173. Full source at examples/django-svelte.