ORMBridge Quick-Start Guide
This guide provides a streamlined setup process for ORMBridge, enabling you to connect your Django backend with a modern frontend in minutes.
Backend Setup (Django)
1. Install Dependencies
bash
# Install Django & DRF if needed
pip install django djangorestframework
# Install ORMBridge
pip install git+https://github.com/ormbridge/ormbridge
# Install CORS headers for cross-origin requests
pip install django-cors-headers2. Configure Django Settings
Note: To use the realtime features, sign up for a free Pusher account. Create a Pusher Channels project and add your credentials to ORMBRIDGE_PUSHER.
python
# Add to INSTALLED_APPS
INSTALLED_APPS = [
# Django defaults...
'rest_framework',
'corsheaders',
'ormbridge.adaptors.django',
'your_app', # Your model app
]
# Add CORS middleware (at the top)
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware', # Must be first
# Other middleware...
]
# Configure CORS
CORS_ALLOWED_ORIGINS = [
"http://localhost:5173", # Vite (Vue, React)
]
# Configure Pusher (for real-time updates)
# Note: You must create an account with Pusher and add your credentials below.
ORMBRIDGE_PUSHER = {
'APP_ID': 'your-pusher-app-id',
'KEY': 'your-pusher-key',
'SECRET': 'your-pusher-secret',
'CLUSTER': 'your-pusher-cluster',
}3. Add ORMBridge URLs
python
# urls.py
from django.urls import path, include
urlpatterns = [
# Your other URLs...
path('ormbridge/', include('ormbridge.adaptors.django.urls', namespace='ormbridge')),
]4. Create Test Models
python
# your_app/models.py
from django.db import models
from django.conf import settings
class Category(models.Model):
name = models.CharField(max_length=100)
slug = models.SlugField(unique=True)
def __str__(self):
return self.name
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
published_date = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
categories = models.ManyToManyField(Category, related_name='posts')
def __str__(self):
return self.title5. Register Models with ORMBridge
python
# your_app/crud.py
from ormbridge.adaptors.django.config import registry
from ormbridge.adaptors.django.permissions import AllowAllPermission
from ormbridge.core.config import ModelConfig
from .models import Post, Category
from django.contrib.auth import get_user_model
User = get_user_model()
# Register Post model
registry.register(
Post,
ModelConfig(
model=Post,
filterable_fields="__all__", # Enable filtering on all fields
searchable_fields={'title', 'content'}, # Enable search on these fields
ordering_fields={'published_date', 'title'}, # Enable ordering
permissions=[AllowAllPermission] # Use proper permissions in production
)
)
# Register Category model
registry.register(
Category,
ModelConfig(
model=Category,
filterable_fields="__all__",
searchable_fields={'name'},
ordering_fields={'name'},
permissions=[AllowAllPermission]
)
)
# Register the Django User model for frontend access
registry.register(
User,
ModelConfig(
model=User,
filterable_fields=("id", "username", "email"), # Customize as needed
searchable_fields={"username", "email"},
ordering_fields={"username"},
permissions=[AllowAllPermission]
)
)6. Run Migrations and Start Server
bash
python manage.py makemigrations
python manage.py migrate
python manage.py runserverFrontend Setup
1. Create Frontend Project
Choose your preferred framework:
Vue (Primary Example)
bash
npm create vue@latest frontend
cd frontend
npm i
npm install https://github.com/ormbridge/ormbridge-clientReact with Vite (React + TypeScript)
bash
npm create vite@latest frontend -- --template react-ts
cd frontend
npm i
npm install https://github.com/ormbridge/ormbridge-client2. Configure ORMBridge Client
Create a file named ormbridge.config.js in your frontend project root:
Note: Remember to use your actual Pusher Pusher app id and cluster.
javascript
export default {
backendConfigs: {
default: {
API_URL: 'http://127.0.0.1:8000/ormbridge',
GENERATED_TYPES_DIR: './src/models',
events: {
type: 'pusher',
pusher: {
clientOptions: {
appKey: 'YOUR_PUSHER_APP_KEY',
cluster: 'YOUR_PUSHER_CLUSTER',
forceTLS: true
}
}
}
},
}
};3. Initialize ORMBridge Configuration
Add the following lines to your main entry file (src/main.js for Vue or src/main.tsx/src/main.ts for React):
javascript
// Import from ormbridge.config.js (REQUIRED for CLI tools to work)
import config from '../ormbridge.config.js';
import { configInstance } from '@ormbridge/core';
// Initialize ORMBridge configuration
configInstance.setConfig(config);Important: The external
ormbridge.config.jsfile is required for the CLI tools to work properly. Always keep your configuration in this file, even if you reference it from your main entry file.
Note: Adjust the import path if your ormbridge.config.js file is located elsewhere relative to your main file.
4. Generate TypeScript Models
Note: Ensure the backend is running in development mode (using
python manage.py runserver) while running thesync-modelscommand.
bash
npx ormbridge sync-modelsUsage Examples
Vue Example (Main Example)
Real-time Updates with LiveView (Vue)
javascript
import { createVueLiveView } from '@ormbridge/core';
import { Post } from '../models';
// In your setup() function:
const posts = ref([]);
const liveQuery = ref(null);
// Initialize LiveView
createVueLiveView(Post.objects.all(), posts)
.then(query => {
liveQuery.value = query;
});
// Add a new post (UI updates instantly)
const addPost = async () => {
if (liveQuery.value) {
await liveQuery.value.create({
title: 'New Post',
content: 'Content',
author: 1
});
}
};
// Clean up on component unmount
onBeforeUnmount(() => {
if (liveQuery.value) {
liveQuery.value.destroy();
}
});React Example
Real-time Updates with LiveView (React)
Create a file named ORMBridgeTest.tsx (adjust the import path as needed):
javascript
import React from 'react';
import { useReactLiveView } from '@ormbridge/core';
import { DummyModel } from '../models/backend1';
function ORMBridgeTest() {
// Use the hook to get data, query, and loading state
const [items, liveQuery, isLoading] = useReactLiveView(DummyModel.objects.all());
const addItem = async () => {
if (liveQuery) {
await liveQuery.create({ name: 'New Item', value: Math.floor(Math.random() * 100) });
}
};
const updateAllItems = async () => {
if (liveQuery) {
await liveQuery.update({ name: 'Updated Item' });
}
};
const deleteAllItems = async () => {
if (liveQuery) {
await liveQuery.delete();
}
};
return (
<div>
<h1>ORMBridge React Test</h1>
<div>
<button onClick={addItem} disabled={isLoading || !liveQuery}>Add Item</button>
<button onClick={updateAllItems} disabled={isLoading || !liveQuery}>Update All</button>
<button onClick={deleteAllItems} disabled={isLoading || !liveQuery}>Delete All</button>
</div>
<div>
<h2>Items: {items.length}</h2>
{isLoading ? (
<p>Loading...</p>
) : (
<ul>
{items.map((item, index) => (
<li key={item.id || index}>
<strong>{item.name}</strong>: {item.value}
</li>
))}
</ul>
)}
</div>
</div>
);
}
export default ORMBridgeTest;Basic Data Fetching Example
javascript
// In a React or Vue component
import { Post } from '../models';
// Fetch posts (async)
const posts = await Post.objects
.filter({ is_published: true })
.orderBy('-published_date')
.all()
.fetch();Creating Data Example
javascript
// Create a new post
await Post.objects.create({
title: 'New Post',
content: 'Content goes here',
author: 1 // User ID
});Key Facts
- ORMBridge automatically synchronizes data between Django and JavaScript.
- Django-like syntax in JavaScript:
.filter(),.get(), etc. - Real-time updates with LiveView + Pusher.
- All CRUD operations are automatically generated.
- Relationships are handled automatically.
- TypeScript models are generated from your Django models.
Remember
- Backend and frontend projects should be in separate directories.
- Register models with ORMBridge via the
crud.pyfile. - You must initialize ORMBridge in your main.js/main.tsx file using
configInstance.setConfig(). - LiveView operations are optimistic (UI updates before the server confirms).
- Never mutate LiveView data arrays directly.