Skip to main content

Django Realtime Events

Project description

🚀 django-realtime-events

Lightweight realtime updates for Django using WebSocket (Django Channels).

django-realtime-events allows you to automatically send realtime events (create, update, delete) from your Django models to the frontend — with minimal setup.


✨ Features

  • ⚡ Realtime model updates (create, update, delete)
  • 🧩 Plug & play (just register your model)
  • 🎯 Per-model WebSocket channel
  • 🔍 Select specific fields (optimized payload)
  • 🔥 Custom serializer support (full control)
  • 🧠 Safe default (ID-only payload)
  • 🔌 Supports Redis & InMemoryChannelLayer
  • 🪶 Lightweight and easy to integrate

📦 Installation

pip install django-realtime-events

Add to your INSTALLED_APPS:

INSTALLED_APPS = [
    ...
    "channels",
    "django_realtime_events",
]

⚙️ Django Channels Setup

1. ASGI Configuration

asgi.py:

from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application
from django_realtime_events.routing import websocket_urlpatterns

application = ProtocolTypeRouter({
    "http": get_asgi_application(),
    "websocket": URLRouter(websocket_urlpatterns),
})

settings.py:

ASGI_APPLICATION = "your_project.asgi.application"

2. Channel Layer (Development)

CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels.layers.InMemoryChannelLayer"
    }
}

3. (Optional) Production with Redis

Install:

pip install channels-redis

Configure:

CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels_redis.core.RedisChannelLayer",
        "CONFIG": {
            "hosts": [("127.0.0.1", 6379)],
        },
    },
}

🚀 Quick Start

1. Register a Model

from django_channels_helper import register_model

register_model("shop.Product")

2. WebSocket Endpoint

ws://localhost:8000/ws/realtime/product/

3. Frontend Example

const socket = new WebSocket("ws://localhost:8000/ws/realtime/product/");

socket.onmessage = function(event) {
    const data = JSON.parse(event.data);
    console.log(data);
};

📡 Event Format

{
  "model": "Product",
  "action": "created",
  "data": {
    "id": 1
  }
}

🎯 Data Configuration

🔹 1. Default (ID only)

register_model("shop.Product")

Output:

{ "id": 1 }

🔹 2. Select Fields

register_model(
    "shop.Product",
    fields=["id", "name"]
)

Output:

{
  "id": 1,
  "name": "Laptop"
}

🔹 3. Custom Serializer 🔥

def product_serializer(obj):
    return {
        "id": obj.id,
        "name": obj.name,
        "category": obj.category.name
    }

register_model(
    "shop.Product",
    serializer=product_serializer
)

Output:

{
  "id": 1,
  "name": "Laptop",
  "category": "Electronics"
}

⚠️ Data Priority Rule

serializer > fields > default (id only)
  • If serializer is provided → it will be used
  • Else if fields is provided → selected fields will be used
  • Else → only id will be sent

🧠 Why ID-only by Default?

The default behavior sends only the model ID to ensure:

  • 🔐 No accidental data exposure
  • ⚡ Minimal payload (fast & efficient)
  • 🧩 Works well with event-driven architecture
  • 🎯 Full flexibility for developers

🧱 Multiple Models

You can register multiple models:

register_model("shop.Product")
register_model("shop.Order")

WebSocket endpoints:

/ws/realtime/product/
/ws/realtime/order/

⚠️ Model Signals Behavior

This package relies on Django model signals:

  • post_save → for create & update
  • post_delete → for delete

🔹 Create

Realtime events are triggered when .save() is called:

product = Product(name="Laptop", category="Electronic")
product.save()

Or:

Product.objects.create(name=name, category=category)

🔹 Update

Must use .save()

product = Product.objects.filter(id=id).first()

if product and name:
    product.name = name
    product.save()

🔹 Delete

Product.objects.filter(id=id).delete()

🧩 Example Use Cases

  • 📊 Live dashboards
  • 🛒 Realtime product updates
  • 🔔 Notification systems
  • 📋 Auto-refresh tables
  • 💬 Chat triggers

⚠️ Best Practices

  • Use fields for better performance
  • Use serializer for relations and transformations
  • Avoid heavy queries inside serializer
  • Use Redis in production environments

🛠️ Requirements

  • Python 3.12+
  • Django 5.1+
  • Django Channels
  • Daphne 4.2+ (Optional)

⚡ Running the Server

This package uses WebSocket via Django Channels, which requires an ASGI server.

Development

If Django Channels is properly configured, you can use:

python manage.py runserver

Alternative (Recommended for stability)

You can also run the project using Daphne:

daphne your_project.asgi:application

If WebSocket is not working with runserver, try using Daphne.


Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django_realtime_events-1.0.3.tar.gz (6.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

django_realtime_events-1.0.3-py3-none-any.whl (7.6 kB view details)

Uploaded Python 3

File details

Details for the file django_realtime_events-1.0.3.tar.gz.

File metadata

  • Download URL: django_realtime_events-1.0.3.tar.gz
  • Upload date:
  • Size: 6.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.5

File hashes

Hashes for django_realtime_events-1.0.3.tar.gz
Algorithm Hash digest
SHA256 5b49fbf536aa2b87c44b6e39762480eb2bb05ff14e851467d8d72244526a52c8
MD5 e0e22d867bf39d9c197429d0ca0628f7
BLAKE2b-256 51c980f0bf0bcb340ba249a1dfa2b2278e22b31f252faa62c5f5f66ed008907a

See more details on using hashes here.

File details

Details for the file django_realtime_events-1.0.3-py3-none-any.whl.

File metadata

File hashes

Hashes for django_realtime_events-1.0.3-py3-none-any.whl
Algorithm Hash digest
SHA256 3c10c2f7c5511775d2c45696e1c5e1cadd9cea515ec5dab801205536699b7304
MD5 f8a658af2f59224cf3ba421871c3590b
BLAKE2b-256 ac6ee792dc1ef04a0c5dd5eefdeb1f7be4583679fd5b1220be86713f0007723e

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page