Metadata-Version: 2.4
Name: django-realtime-events
Version: 1.0.2
Summary: Django Realtime Events
Author-email: Akhbarul Hadi <akhbarulhadi44@gmail.com>
License: MIT
Keywords: django,realtime,websocket,channels
Requires-Python: >=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: Django>=5.1
Requires-Dist: channels>=4.1
Dynamic: license-file

# 🚀 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

```bash
pip install django-realtime-events
```

Add to your `INSTALLED_APPS`:

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

---

## ⚙️ Django Channels Setup

### 1. ASGI Configuration

asgi.py:
```python
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:
```python
ASGI_APPLICATION = "your_project.asgi.application"
```

---

### 2. Channel Layer (Development)

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

---

### 3. (Optional) Production with Redis

Install:

```bash
pip install channels-redis
```

Configure:

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

---

## 🚀 Quick Start

### 1. Register a Model

```python
from django_channels_helper import register_model

register_model("shop.Product")
```

---

### 2. WebSocket Endpoint

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

---

### 3. Frontend Example

```javascript
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

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

---

## 🎯 Data Configuration

### 🔹 1. Default (ID only)

```python
register_model("shop.Product")
```

Output:

```json
{ "id": 1 }
```

---

### 🔹 2. Select Fields

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

Output:

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

---

### 🔹 3. Custom Serializer 🔥

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

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

Output:

```json
{
  "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:

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

WebSocket endpoints:

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

---

## 🧩 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
python manage.py runserver
```

#### Alternative (Recommended for stability)

You can also run the project using Daphne:
```python
daphne your_project.asgi:application
```

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


---
