Overview
Bar Galileo implements a real-time notification system using Django Channels and WebSockets. This architecture allows the backend to push instant notifications to authenticated users without polling, creating a responsive and modern user experience.Notifications are persisted in the database and displayed as floating pop-ups in the browser, ensuring users never miss important events.
Architecture
The notification system consists of several interconnected components:Components
| Component | Purpose | Location |
|---|---|---|
models.py | Database model for persisting notifications | notifications/models.py |
consumers.py | WebSocket consumer handling connections | notifications/consumers.py |
utils.py | Helper function to send notifications | notifications/utils.py |
views.py | REST API for notification history | notifications/views.py |
routing.py | WebSocket URL routing | notifications/routing.py |
Configuration
INSTALLED_APPS = [
# ...
'channels',
'notifications',
]
# ASGI application for WebSocket support
ASGI_APPLICATION = 'bar_galileo.asgi.application'
# Channel layer configuration
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels.layers.InMemoryChannelLayer",
# For production, use Redis:
# "BACKEND": "channels_redis.core.RedisChannelLayer",
# "CONFIG": {"hosts": [("127.0.0.1", 6379)]},
}
}
InMemoryChannelLayer is suitable for development only. For production deployments, use Redis-backed channel layers for proper scaling and reliability.import os
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
import notifications.routing
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bar_galileo.settings")
application = ProtocolTypeRouter({
"http": get_asgi_application(),
"websocket": AuthMiddlewareStack(
URLRouter(
notifications.routing.websocket_urlpatterns
)
),
})
Database Model
Notifications are stored using a simple but effective schema:notifications/models.py
Fields
- usuario: Foreign key to the User model (notification recipient)
- mensaje: Text content of the notification
- leida: Boolean flag indicating if the notification has been read
- fecha: Automatic timestamp when notification was created
Sending Notifications
Basic Usage
Thenotificar_usuario() utility function provides a simple interface for sending notifications:
Implementation
The utility function handles both database persistence and real-time delivery:notifications/utils.py
Common Use Cases
WebSocket Consumer
The consumer handles WebSocket connections and message routing:notifications/consumers.py
Connection Flow
- User loads page → JavaScript establishes WebSocket connection
- Authentication check → Consumer verifies user is authenticated
- Group join → User added to
user_{id}channel group - Event triggered →
notificar_usuario()called from backend - Message sent → Channel layer routes to user’s WebSocket
- Display notification → Frontend shows toast/pop-up
REST API Endpoints
Get Notification History
Mark as Read
Get Pending Notifications
Frontend Integration
HTML Setup
Add the notification container to your base template:templates/base.html
JavaScript WebSocket Connection
static/js/notifications/notifications.js
Best Practices
Keep messages concise and actionable
Keep messages concise and actionable
Notifications should be brief and provide clear information about what happened.Good examples:
- “Pedido #123 completado - Mesa 5”
- “Stock bajo: 5 unidades de Cerveza Corona”
- “Nuevo backup creado exitosamente”
- “OK” (too vague)
- “Has cargado la página” (spam)
- Long multi-sentence explanations
Don't over-notify users
Don't over-notify users
Only send notifications for important events that require user attention. Over-notification leads to notification fatigue and users ignoring or disabling them.
Never include sensitive data
Never include sensitive data
Notifications may be visible on screen or in logs. Avoid including:
- Passwords or credentials
- Credit card numbers
- Personal identification numbers
- Confidential business data
Test notification delivery
Test notification delivery
Always test notifications in both development and production environments:
Production Deployment
For production environments, replace the in-memory channel layer with Redis:CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG": {
"hosts": [("127.0.0.1", 6379)],
# Optional: add authentication
# "password": "your-redis-password",
},
},
}
Troubleshooting
WebSocket not connecting
- Verify Channels is installed:
pip list | grep channels - Check
ASGI_APPLICATIONsetting insettings.py - Inspect browser console for connection errors
- Ensure WebSocket URL matches routing configuration
Notifications not displayed
- Confirm
#notificaciones-flotantesdiv exists in HTML - Verify JavaScript files are loaded (check Network tab)
- Check browser console for JavaScript errors
- Test WebSocket connection manually with browser tools
Notifications not saved to database
- Run migrations:
python manage.py migrate notifications - Verify user is authenticated
- Check database logs for constraint violations
- Confirm
Notificacionmodel is registered in admin
Redis connection errors (production)
Next Steps
RAG Chat
Learn about document Q&A with RAG
Integrations
Explore third-party integrations
