Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Django
  • Views
  • Model
  • Template
  • Forms
  • Jinja
  • Python SQLite
  • Flask
  • Json
  • Postman
  • Interview Ques
  • MongoDB
  • Python MongoDB
  • Python Database
  • ReactJS
  • Vue.js
Open In App
Next Article:
Learn to use Websockets with Django
Next article icon

Learn to use Websockets with Django

Last Updated : 03 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Django Channels is an extension of the Django framework that allows for handling WebSockets, HTTP2, and other protocols. It integrates with Django’s existing ORM and works seamlessly alongside Django views. In this tutorial, we will create a small Django project that displays "GeeksforGeeks" on the homepage and demonstrates how to set up WebSockets using Django Channels.

Step-by-Step Guide How to use Django channels for websocket?

1. Setting Up the Django Project

First, let's create a new Django project. Open your terminal and run the following commands:

# Create a virtual environment
python -m venv myenv

# Activate the virtual environment
# On Windows
myenv\Scripts\activate
# On macOS/Linux
source myenv/bin/activate

# Install Django
pip install django

# Create a new Django project
django-admin startproject myproject

# Navigate to the project directory
cd myproject

# Start a new Django app
python manage.py startapp myapp

2. Installing Django Channels

Next, install Django Channels:

pip install channels

Add Channels to your INSTALLED_APPS in myproject/settings.py:

INSTALLED_APPS = [
...
'channels',
'myapp',
]
jj


3. Configuring ASGI

Django Channels requires an ASGI configuration. Update your myproject/asgi.py to include Channels:

Python
import os import django from channels.routing import get_default_application  os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') django.setup() application = get_default_application() 

And update your myproject/settings.py to specify the ASGI application:

Python
ASGI_APPLICATION = "myproject.asgi.application" 

4. Creating a WebSocket Consumer

Create a WebSocket consumer in myapp/consumers.py:

Python
import json from channels.generic.websocket import WebsocketConsumer  class MyConsumer(WebsocketConsumer):     def connect(self):         self.accept()         self.send(text_data=json.dumps({             'message': 'GeeksforGeeks'         }))          def disconnect(self, close_code):         pass          def receive(self, text_data):         pass 

5. Defining the Routing

Create a routing configuration in myapp/routing.py:

Python
from django.urls import re_path from .consumers import MyConsumer  websocket_urlpatterns = [     re_path(r'ws/somepath/$', MyConsumer.as_asgi()), ] 

Update myproject/asgi.py to include the routing:

Python
from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from myapp.routing import websocket_urlpatterns  application = ProtocolTypeRouter({     "http": get_default_application(),     "websocket": AuthMiddlewareStack(         URLRouter(             websocket_urlpatterns         )     ), }) 

6. Creating the Django View

Now, create a simple view to render the homepage in myapp/views.py:

Python
from django.shortcuts import render  def home(request):     return render(request, 'home.html') 

Add a URL pattern in myapp/urls.py:

Python
from django.urls import path from .views import home  urlpatterns = [     path('', home, name='home'), ] 

Include myapp URLs in myproject/urls.py:

Python
from django.contrib import admin from django.urls import path, include  urlpatterns = [     path('admin/', admin.site.urls),     path('', include('myapp.urls')), ] 

7. Creating the HTML Template

Create a template file myapp/templates/home.html:

HTML
<!DOCTYPE html> <html> <head>     <title>GeeksforGeeks</title> </head> <body>     <h1>GeeksforGeeks</h1>     <script>         const socket = new WebSocket('ws://' + window.location.host + '/ws/somepath/');          socket.onmessage = function(event) {             const data = JSON.parse(event.data);             console.log(data.message);         };     </script> </body> </html> 

8. Running the Server

Finally, run the Django development server:

python manage.py migrate
python manage.py runserver

Navigate to http://127.0.0.1:8000 in your web browser. You should see "GeeksforGeeks" on the homepage and a WebSocket connection being established in the background.

Inspecting WebSocket Connection

Open Developer Tools:

  • Open your web browser (e.g., Google Chrome).
  • Navigate to http://127.0.0.1:8000 where your Django application is running.
  • Right-click on the page and select Inspect or press Ctrl+Shift+I (Windows/Linux) or Cmd+Option+I (Mac) to open the Developer Tools.

Go to the Network Tab:

  • In the Developer Tools, click on the Network tab.
  • This tab displays all network requests made by the page.

Filter for WebSocket:

  • In the Network tab, you will see a list of network requests.
  • To filter and see only WebSocket connections, click on the WS button which stands for WebSockets.

Inspect the WebSocket Connection:

  • You should see a connection to your WebSocket URL (ws://127.0.0.1:8000/ws/somepath/).
  • Click on this connection to inspect its details.
  • Inside, you can see frames that show the messages being sent and received through the WebSocket.

Video Demonstration

Conclusion

You have successfully set up a Django project with Django Channels to handle WebSockets. This setup allows for real-time communication between the server and clients, enabling dynamic and interactive web applications. This example covers the basics, and you can extend it by implementing more complex WebSocket interactions as needed.


Next Article
Learn to use Websockets with Django

P

prathamsahani0368
Improve
Article Tags :
  • Python
  • Python Django
Practice Tags :
  • python

Similar Reads

    How To Use WebSocket With FastAPI
    In this article, we will see what a WebSocket is, why we need Websocket, and how Websocket can be used to make real-time applications. We will see HTTP requests getting upgraded to web socket and how it will allow the server to send data to the client without the client having to send multiple HTTP
    5 min read
    How to Use WebSocket and Load Balancers?
    WebSockets are a technology that allows websites and servers to talk to each other in real time. It's like having a phone line that stays open between your browser and a server, so they can send messages back and forth quickly and efficiently without having to reconnect all the time. Important Topic
    7 min read
    How to Integrate WebSockets with React Redux
    Integrating WebSockets with Redux allows for real-time bidirectional communication between the client (e.g. a web browser) and the server. This enables applications to push data from the server to the client instantly, facilitating features such as real-time updates, live notifications, and chat app
    6 min read
    How to Send WebSocket Requests with Postman ?
    This article will show how to send WebSocket requests in Postman. Postman is a popular collaborative platform for API development. It offers different tools for designing, debugging, and testing an API, making it more efficient. WebSocket is an advanced technology used for real-time bidirectional co
    3 min read
    Documenting Websocket APIs with Swagger
    WebSocket APIs offer a powerful way to create real-time, interactive applications by enabling bidirectional communication between clients and servers. Documenting these APIs is crucial for developers to understand and utilize them effectively. Swagger (now known as OpenAPI) is a widely used framewor
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences