How can we use Django Channels (a special Django feature) to create apps where things update instantly without refreshing the page?
Work your way through the official Django Channels Tutorial. Once you’ve done that and understand what each function is doing, you’ll know everything you need to know to get started.
Note: You only need to use Channels if you want the server to issue the updates to the page. (A “push” situation.) If you want an event happening in the page to do a partial update (such as clicking on an icon), you can do that without Channels.
Since You Mentioned Django Channels for Live Chat, You are specially focused on WebSocket based communications.
For Building a Live Chat type platform you need a message broker like REDIS, for Dynamic memory for your django workers,
The Documentation of Django Channels are very straight forward.
It Highly depends on Async fucntions so, you have a consumers.py(basically like views.py) and a routing.py(identical to urls.py). After that you need modify the Asgi.py file for the deployment and testing, Here is an example ( I keep it with me most of the time ).
import os
import django
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.security.websocket import AllowedHostsOriginValidator
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'website.settings')
django.setup()
from chat.routing import websocket_urlpatterns
from channels.middleware import BaseMiddleware
class SimpleAuthMiddleware(BaseMiddleware):
async def __call__(self, scope, receive, send):
scope["user"] = None # No authentication
return await super().__call__(scope, receive, send)
application = ProtocolTypeRouter(
{
"http": get_asgi_application(),
# Just HTTP for now. (We can add other protocols later.)
"websocket": AllowedHostsOriginValidator(
SimpleAuthMiddleware(URLRouter(websocket_urlpatterns))
),
}
)
And then you can depoly it with Uvicorn.
This is How i Built most of the realtime django apps.
I’ve written a guide on how to build a chat app with channels and htmx. Maybe it will be useful?