← Back to Blog

Django + Vue: async Django backend, Vue 3 composables

·9 min read

This stack combines Django's backend maturity with Vue 3's Composition API and reactivity system. The server integration is a standard Django view, import views, and call mount_django(urlpatterns). The Vue side uses TanStack Vue Query wrapped by @pyrpc/vue to expose fully typed composables like useQuery and useMutation.

Server (same as django-react)

# 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: must import views to trigger registration
from . import views
from pyrpc_django import mount_django
urlpatterns = [...]
mount_django(urlpatterns)

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

Client

// src/pyrpc.ts
import { createPyrpcVue } from "@pyrpc/vue"
import type { Types } from "@pyrpc/types"

export const pyrpc = createPyrpcVue<Types>({
  baseUrl: import.meta.env.VITE_API_URL ?? "http://localhost:8000",
})
// src/main.ts
createApp(App).use(pyrpc.plugin).mount("#app")
<!-- src/App.vue -->
<script setup lang="ts">
import { ref } from "vue"
import { pyrpc } from "./pyrpc"

const name = ref("")
const { data: greeting, isPending } = pyrpc.greet.createQuery(() => ({ name: "Django User" }))
const { data: item } = pyrpc.read_item.createQuery(() => ({ item_id: 42, q: "django-test" }))
const createItem = pyrpc.create_item.createMutation()
</script>

<template>
  <p v-if="isPending">Loading…</p>
  <pre v-else>{{ JSON.stringify(greeting) }}</pre>
  <pre>{{ JSON.stringify(item) }}</pre>
  <input v-model="name" />
  <button @click="createItem.mutate({ name })" :disabled="createItem.isPending.value">
    {{ createItem.isPending.value ? "Creating…" : "Create" }}
  </button>
  <pre v-if="createItem.isSuccess.value">{{ JSON.stringify(createItem.data.value) }}</pre>
</template>

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-vue.