Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Django Channels Tutorial

Introduction to Django Channels

Django Channels is a library that extends Django to handle WebSockets, chat protocols, IoT protocols, and other asynchronous web protocols. It allows Django to support real-time functionality, such as chat applications and live updates.

Installation

To get started with Django Channels, you need to install it using pip. Run the following command:

pip install channels

Setting Up Channels

After installation, you need to add Channels to your Django project's settings. Open your settings.py file and add 'channels' to your INSTALLED_APPS:

INSTALLED_APPS = [
  'django.contrib.admin',
  'django.contrib.auth',
  'django.contrib.contenttypes',
  'django.contrib.sessions',
  'django.contrib.messages',
  'django.contrib.staticfiles',
  'channels',
]

Next, you need to set the ASGI application. Add the following line to the end of your settings.py:

ASGI_APPLICATION = 'your_project_name.asgi.application'

Creating the ASGI Configuration

Create a new file named asgi.py in your project directory (the same directory as settings.py and wsgi.py). Add the following code to asgi.py:

import os

from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'your_project_name.settings')

application = ProtocolTypeRouter({
  'http': get_asgi_application(),
  'websocket': AuthMiddlewareStack(
    URLRouter(
      # Your routing here
    )
  ),
})

Routing

To handle WebSocket connections, you need to define routing configurations. Create a file named routing.py in one of your Django apps and add the following code:

from django.urls import re_path
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from channels.security.websocket import AllowedHostsOriginValidator

from your_app_name.consumers import YourConsumer

websocket_urlpatterns = [
  re_path(r'ws/some_path/$', YourConsumer.as_asgi()),
]

Creating a Consumer

Consumers are the equivalent of Django views for handling WebSocket connections. Create a file named consumers.py in your app and add the following code:

import json
from channels.generic.websocket import AsyncWebsocketConsumer

class YourConsumer(AsyncWebsocketConsumer):
  async def connect(self):
    await self.accept()

  async def disconnect(self, close_code):
    pass

  async def receive(self, text_data):
    text_data_json = json.loads(text_data)
    message = text_data_json['message']

    await self.send(text_data=json.dumps({
      'message': message
    }))

Running the Server

To run your Django Channels server, use the following command:

daphne -p 8001 your_project_name.asgi:application

You can still use Django's runserver command for HTTP traffic, but for WebSocket traffic, use Daphne or another ASGI server.

Testing Your Setup

To test your WebSocket setup, create an HTML file with the following content:

<!DOCTYPE html>
<html>
<head>
<title>WebSocket Test</title>
</head>
<body>
<h1>WebSocket Test</h1>
<script>
  var ws = new WebSocket('ws://localhost:8001/ws/some_path/');
  ws.onmessage = function(event) {
    var message = JSON.parse(event.data).message;
    console.log('Message from server: ', message);
  };
  ws.onopen = function(event) {
    ws.send(JSON.stringify({
      'message': 'Hello, Server!'
    }));
  };
</script>
</body>
</html>

Open this HTML file in your browser and check the console for messages from the server.