<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Saurabh on Medium]]></title>
        <description><![CDATA[Stories by Saurabh on Medium]]></description>
        <link>https://medium.com/@saurabhgujjar?source=rss-857a55c5b646------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*upa9YW4y16sYa1RM1LhZtA@2x.jpeg</url>
            <title>Stories by Saurabh on Medium</title>
            <link>https://medium.com/@saurabhgujjar?source=rss-857a55c5b646------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 21:29:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@saurabhgujjar/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building Real-Time Web Applications with Django Channels]]></title>
            <link>https://awstip.com/building-real-time-web-applications-with-django-channels-656087038335?source=rss-857a55c5b646------2</link>
            <guid isPermaLink="false">https://medium.com/p/656087038335</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Saurabh]]></dc:creator>
            <pubDate>Tue, 11 Jul 2023 19:59:31 GMT</pubDate>
            <atom:updated>2023-07-14T14:24:36.814Z</atom:updated>
            <content:encoded><![CDATA[<p>Python, Django, Django Channels, Websocket, Realtime Chat App</p><p>In the world of web development, real-time applications have become increasingly popular, enabling users to experience instantaneous updates and seamless interactions. Traditionally, building real-time functionality in web applications was a complex task, often requiring the use of technologies like WebSockets. Django, a popular Python web framework, provides a powerful solution for building web applications. However, Django primarily follows a request-response model, which is not suitable for real-time applications. To address this limitation, Django Channels was introduced as an extension to Django, enabling developers to build real-time web applications easily.</p><p>In this article, we will explore the fundamentals of Django Channels and demonstrate how to build a real-time chat application using this framework. By the end, you will have a solid understanding of Django Channels and be able to incorporate real-time features into your Django projects.</p><h4>What is Django Channels?</h4><p>Django Channels is an open-source third-party package for Django that extends its capabilities to handle WebSockets, HTTP/2, and other asynchronous protocols. It allows developers to handle WebSocket connections, background tasks, and other asynchronous operations in Django applications. Django Channels is built on top of the ASGI (Asynchronous Server Gateway Interface) specification, which provides an interface between web servers and Python web applications. With Django Channels, you can create web applications that deliver real-time updates, chat functionality, live notifications, and more.</p><blockquote><strong>Prerequisites:</strong> To follow along with this tutorial, you should have a basic understanding of Django, Python, and JavaScript.</blockquote><h4>Setting Up Django Channels:</h4><ol><li>Create a new Django project:</li></ol><p>$ django-admin startproject real_time_app</p><p>2. Install Django Channels:</p><p>$ pip install channels</p><p>3. Configure Channels in Django settings:</p><p>Now, let’s configure Django Channels in our project settings. Open settings.py and add ‘channels’ to the INSTALLED_APPS list:</p><pre># settings.py<br><br>INSTALLED_APPS = [<br>    # Other apps...<br>    &#39;channels&#39;,<br>]</pre><p>Additionally, add the following code at the end of the file to configure the Channels layer:</p><pre>#settings.py<br><br>ASGI_APPLICATION = &#39;real_time_app.routing.application&#39;<br>CHANNEL_LAYERS = {<br>    &#39;default&#39;: {<br>        &#39;BACKEND&#39;: &#39;channels.layers.InMemoryChannelLayer&#39;,<br>    },<br>}</pre><p>This configuration sets up an in-memory channel layer, suitable for development and testing purposes. In a production environment, you would typically use a more robust channel layer, such as <strong>Redis</strong> or <strong>RabbitMQ</strong>.</p><p>4. Create a new file called routing.py in your project’s root directory:</p><pre># routing.py<br><br>from channels.routing import ProtocolTypeRouter, URLRouter<br>from django.urls import path<br>from . import consumers<br><br>application = ProtocolTypeRouter({<br>    &#39;http&#39;: get_asgi_application(),<br>    &#39;websocket&#39;: AuthMiddlewareStack(<br>        URLRouter([<br>            path(&#39;ws/chat/&#39;, consumers.ChatConsumer.as_asgi()),<br>        ])<br>    ),<br>})</pre><h4>Building the Chat Application:</h4><ol><li>Create a new Django app:</li></ol><p>$ python manage.py startapp chat</p><p>2. Create a new file called consumers.py in the chat app directory:</p><pre># consumers.py<br><br>from channels.generic.websocket import AsyncWebsocketConsumer<br><br>class ChatConsumer(AsyncWebsocketConsumer):<br>    async def connect(self):<br>        self.room_name = &#39;general&#39;<br>        self.room_group_name = &#39;chat_%s&#39; % self.room_name<br><br>        # Join room group<br>        await self.channel_layer.group_add(<br>            self.room_group_name,<br>            self.channel_name<br>        )<br><br>        await self.accept()<br><br>    async def disconnect(self, close_code):<br>        # Leave room group<br>        await self.channel_layer.group_discard(<br>            self.room_group_name,<br>            self.channel_name<br>        )<br><br>    async def receive(self, text_data):<br>        # Send message to room group<br>        await self.channel_layer.group_send(<br>            self.room_group_name,<br>            {<br>                &#39;type&#39;: &#39;chat_message&#39;,<br>                &#39;message&#39;: text_data<br>            }<br>        )<br><br>    async def chat_message(self, event):<br>        # Receive message from room group<br>        message = event[&#39;message&#39;]<br><br>        # Send message to WebSocket<br>        await self.send(text_data=message)</pre><p>Here, we define a WebSocket consumer class, ChatConsumer, that inherits from AsyncWebsocketConsumer. This class provides methods to handle WebSocket connections, disconnections, and incoming messages. We override the connect, disconnect, and receive methods to handle WebSocket connection events.</p><p>3. Create a new file called chat.html in the templates directory:</p><pre>&lt;!-- chat.html --&gt;<br><br>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>    &lt;title&gt;Real-Time Chat&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;h1&gt;Real-Time Chat&lt;/h1&gt;<br>    &lt;div id=&quot;chat-log&quot;&gt;&lt;/div&gt;<br>    &lt;input id=&quot;chat-message-input&quot; type=&quot;text&quot;&gt;<br>    &lt;button id=&quot;chat-message-submit&quot; type=&quot;button&quot;&gt;Send&lt;/button&gt;<br>&lt;/body&gt;<br>&lt;script&gt;<br>    const chatSocket = new WebSocket(<br>        &#39;ws://&#39; + window.location.host +<br>        &#39;/ws/chat/&#39;<br>    );<br><br>    chatSocket.onmessage = function(e) {<br>        const message = JSON.parse(e.data);<br>        document.querySelector(&#39;#chat-log&#39;).innerHTML += &#39;&lt;br&gt;&#39; + message;<br>    };<br><br>    document.querySelector(&#39;#chat-message-submit&#39;).onclick = function(e) {<br>        const messageInputDom = document.querySelector(&#39;#chat-message-input&#39;);<br>        const message = messageInputDom.value;<br>        chatSocket.send(JSON.stringify(message));<br>        messageInputDom.value = &#39;&#39;;<br>    };<br>&lt;/script&gt;<br>&lt;/html&gt;</pre><p>4. Update the urls.py file in the project’s root directory:</p><pre># urls.py<br><br>from django.urls import path<br>from chat.views import chat_room<br><br>urlpatterns = [<br>    # Other paths...<br>    path(&#39;chat/&#39;, chat_room, name=&#39;chat_room&#39;),<br>]</pre><p>5. Create a new file called views.py in the chat app directory:</p><pre># views.py<br><br>from django.shortcuts import render<br><br>def chat_room(request):<br>    return render(request, &#39;chat.html&#39;)</pre><h4>Testing the Chat Application:</h4><ol><li>Start the development server:</li></ol><p>$ python manage.py runserver</p><p>2. Visit <a href="http://localhost:8000/chat/">http://localhost:8000/chat/</a> in your browser and open multiple tabs.</p><p>3. Start a conversation by typing a message and hitting the “Send” button. The message will be broadcasted to all connected clients in real-time.</p><p>Congratulations! You have successfully built a real-time web application using Django Channels. This example demonstrates the basics of Django Channels and how it can be used to handle WebSocket connections and real-time communication.</p><p>In this article, we learned how to set up Django Channels and build a real-time chat application. By following these steps, you can extend the functionality of your Django applications to include real-time communication, opening doors for a wide range of real-time web applications.</p><p>Happy coding!</p><blockquote>Thank you for reading! Hit the <strong>Follow</strong> button for more such content.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=656087038335" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/building-real-time-web-applications-with-django-channels-656087038335">Building Real-Time Web Applications with Django Channels</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing Database Performance in Django with Advanced Querying Techniques]]></title>
            <link>https://awstip.com/optimizing-database-performance-in-django-with-advanced-querying-techniques-9bff269e45b8?source=rss-857a55c5b646------2</link>
            <guid isPermaLink="false">https://medium.com/p/9bff269e45b8</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Saurabh]]></dc:creator>
            <pubDate>Thu, 06 Jul 2023 20:56:58 GMT</pubDate>
            <atom:updated>2023-07-14T14:24:48.734Z</atom:updated>
            <content:encoded><![CDATA[<p>Django Performance, Database Optimization, Querying Techniques, Web Development, Performance Optimization, ORM (Object-Relational Mapping), Query Optimization, Scalability, Database Management, Backend Development, SQL, Caching, Indexing, Python, Django</p><h3>Introduction</h3><p>In today’s world of data-driven applications, efficient database performance is crucial for delivering fast and efficient user experiences. Django, a powerful Python web framework, provides a robust and user-friendly Object-Relational Mapping (ORM) system that abstracts away the complexities of database interactions. However, as applications grow and handle larger datasets, developers need to employ advanced querying techniques to ensure optimal performance. In this article, we will explore various strategies to optimize database performance in Django using advanced querying techniques.</p><figure><img alt="django database optimization" src="https://cdn-images-1.medium.com/max/976/1*tw4iPzVn8YkEEDiH7MBzBw.jpeg" /><figcaption>Optimizing Database Performance in Django with Advanced Querying Techniques</figcaption></figure><h4>Understand QuerySets and Lazy Evaluation:</h4><p>Django’s QuerySets serve as the foundation for working with databases. By understanding the intricacies of QuerySets, you can optimize your database queries and reduce unnecessary overhead. Some key techniques include:</p><ol><li><strong>Selecting Only Necessary Fields:</strong> Use values() or only() methods to retrieve only the required fields from the database. This minimizes data transfer and improves performance.</li><li><strong>Filtering Results:</strong> Utilize Django’s filter options like exclude(), filter(), and Q objects to narrow down your query results efficiently. Combine multiple conditions with logical operators to optimize complex queries.</li><li><strong>QuerySet Caching:</strong> Leverage Django’s caching mechanisms, such as cache_page() and cache_control(), to store frequently accessed QuerySets in memory and reduce database hits.</li></ol><p>QuerySets in Django are lazily evaluated, meaning that database queries are executed only when necessary. This behavior allows us to chain multiple filters, slices, and other query operations without actually hitting the database. By understanding how querysets work, we can minimize unnecessary database calls and improve performance.</p><figure><img alt="working of django orm" src="https://cdn-images-1.medium.com/max/879/1*jR_naUKtTlBvjf1NCvqTSg.png" /><figcaption>working of django orm</figcaption></figure><h4>Limit Database Queries with Select_related and Prefetch_related:</h4><p>Django’s ORM supports two powerful methods, select_related and prefetch_related, to reduce the number of database queries required for retrieving related objects. select_related fetches related objects using a JOIN operation, reducing the need for subsequent queries. prefetch_related fetches the related objects in separate queries and caches them, reducing the impact of the N+1 query problem. Properly utilizing these methods can significantly improve performance when dealing with related objects.</p><h4>Aggregation and Annotation:</h4><p>Django’s aggregation and annotation features enable you to perform complex computations on the database side, reducing the need for extensive post-processing in your application code. These techniques include:</p><ol><li><strong>Aggregating Results:</strong> Use Django’s aggregate() function to calculate sums, averages, counts, or other aggregate values directly in the database. This minimizes data transfer and optimizes performance.</li><li><strong>Annotating QuerySets:</strong> Leverage the annotate() function to add computed values as additional fields to your QuerySets. This allows you to avoid repetitive calculations and boosts query efficiency.</li></ol><h4>Use Raw SQL for Complex Queries:</h4><p>While Django’s ORM provides an elegant and convenient way to interact with the database, there are cases where Django’s ORM might not provide the flexibility or performance required for complex queries. In such situations, you can resort to raw SQL queries. Although raw SQL queries bypass Django’s query building and may require extra caution, they can be significantly faster for specific scenarios. For complex queries involving multiple joins, subqueries, or custom aggregations, raw SQL queries can often outperform their ORM counterparts.</p><ol><li><strong>Using </strong><strong>raw() Method:</strong> Django provides a raw() method to execute raw SQL queries safely, ensuring protection against SQL injection attacks.. Ensure that you use parameter binding to prevent SQL injection vulnerabilities.</li><li><strong>Stored Procedures and Database Functions:</strong> If your database supports stored procedures or custom database functions, consider utilizing them to perform complex calculations and operations directly on the database server.</li></ol><h4>Utilize Database Indexing:</h4><p>Database indexing is a fundamental technique for optimizing query performance. Django allows us to define indexes on model fields to speed up common queries. By carefully selecting which fields to index, we can reduce the number of disk reads and improve search speed. Additionally, Django provides tools like django.db.connection.queries, which can help identify slow queries that may benefit from additional indexing. Consider the following indexing techniques:</p><ol><li><strong>Primary Keys and Foreign Keys:</strong> By default, Django adds an index to primary keys and foreign keys. However, you can enhance performance by adding additional indexes on fields frequently used for filtering or ordering.</li><li><strong>Compound Indexes:</strong> If your queries involve multiple fields, consider creating compound indexes. These indexes optimize queries that rely on a combination of fields, significantly improving performance.</li><li><strong>Unique Constraints:</strong> Ensure that fields with unique constraints have corresponding unique indexes. This not only enforces data integrity but also enhances query performance.</li></ol><h4>Employ Database-level Caching:</h4><p>Caching can dramatically improve performance by storing frequently accessed data in memory. Django supports various caching backends, such as Memcached and Redis, which can be utilized at the database level. By caching query results or even HTML fragments, we can reduce the need for repetitive database queries, resulting in significant performance gains.</p><h4>Implement Database Query Logging and Optimize Query Performance:</h4><p>Regularly monitoring query performance is essential to identify bottlenecks and areas for improvement. Django provides a powerful debugging toolbar (django-debug-toolbar) that displays query execution time and helps identify slow queries. By enabling query logging during development or debugging, you can identify and optimize slow queries, unnecessary repetitions, or poorly performing database operations. Additionally, using tools like Django Silk or Django DevServer can provide detailed insights into query performance, enabling developers to fine-tune their queries for optimal speed.</p><h3>Conclusion</h3><p>Optimizing database performance is essential for building scalable and efficient Django applications. By employing advanced querying techniques, such as understanding QuerySets, indexing appropriately, leveraging aggregation and annotation, and utilizing raw SQL queries when necessary, you can significantly enhance your application’s efficiency. Continuously monitoring and profiling your application’s performance will help you identify bottlenecks and further optimize your database queries. With these techniques in your toolbox, you’ll be well-equipped to create blazing-fast Django applications that scale seamlessly.</p><blockquote>Hey, please <strong>Follow </strong>me<strong> </strong>for more such amazing articles! It motivates me to write more stuff related to <strong>Python Django Stack</strong>.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9bff269e45b8" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/optimizing-database-performance-in-django-with-advanced-querying-techniques-9bff269e45b8">Optimizing Database Performance in Django with Advanced Querying Techniques</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond the Web: Django’s Secret Power]]></title>
            <link>https://saurabhgujjar.medium.com/beyond-the-web-djangos-secret-power-ef27bfd7ed97?source=rss-857a55c5b646------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef27bfd7ed97</guid>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[web-design]]></category>
            <dc:creator><![CDATA[Saurabh]]></dc:creator>
            <pubDate>Wed, 05 Jul 2023 21:23:06 GMT</pubDate>
            <atom:updated>2023-07-05T21:28:13.513Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction</strong></h3><p>Django, the popular Python web framework, is widely known for its ability to rapidly develop robust web applications. However, its true power extends beyond the web. In this article, we will explore the secret power of Django and its potential applications in non-web contexts. From command-line utilities to backend data processing and API development, Django proves to be a versatile tool that can enhance various aspects of software development beyond traditional web development.</p><figure><img alt="Beyond the Web: Django’s Secret Power Why Django? Best Backend Framework, Web Development with Django: Django’s untapped potential beyond web development." src="https://cdn-images-1.medium.com/max/750/1*8Gr2pMDdhQVf89D6TLuVag.jpeg" /><figcaption>Beyond the Web: Django’s Secret Power</figcaption></figure><h4><strong>1. Command-Line Utilities with Django:</strong></h4><p>While Django is primarily designed for web development, it also provides a powerful command-line interface (CLI) that can be leveraged to build command-line utilities. With Django’s management commands, developers can easily create custom scripts to perform various tasks, such as data migration, data scraping, or running periodic jobs. The same robustness and ease of use that Django provides for web development can be utilized in creating efficient and maintainable command-line tools.</p><h4>2. Backend Data Processing:</h4><p>Django’s ORM (Object-Relational Mapping) and powerful database support make it an excellent choice for backend data processing tasks. By leveraging Django’s models and database connectivity, developers can build data processing pipelines, perform complex data transformations, and automate data ingestion processes. The Django ORM’s flexibility and query capabilities allow for efficient data filtering, aggregation, and manipulation, making it a valuable tool for data-centric applications beyond the web.</p><h4><strong>3. Building APIs with Django Rest Framework:</strong></h4><p>Django Rest Framework (DRF), an extension to Django, enables the creation of robust and scalable APIs. While APIs are commonly associated with web development, they play a crucial role in modern software architecture beyond the web. With DRF, developers can build APIs that power mobile applications, desktop applications, or even IoT (Internet of Things) devices. Django’s extensive support for authentication, serialization, and request handling makes it an ideal choice for building APIs in diverse application contexts.</p><h4><strong>4. Task Scheduling and Background Jobs:</strong></h4><p>Django’s extensible architecture allows for seamless integration with task scheduling and background job processing systems. By utilizing libraries like Celery or Django Channels, developers can offload computationally intensive tasks or long-running processes to be executed asynchronously. This capability is invaluable for handling time-consuming operations such as sending emails, generating reports, or performing batch processing tasks. Django’s ability to handle these tasks reliably and efficiently ensures that the main application remains responsive and scalable.</p><h4><strong>5. Microservices and Service-Oriented Architecture:</strong></h4><p>Django’s modular design and flexible component architecture lend themselves well to building microservices and service-oriented architectures (SOA). By decoupling specific functionalities into separate Django applications, developers can create loosely coupled services that communicate through APIs. This approach enables the development of highly scalable and maintainable systems, where each service can be developed, deployed, and scaled independently. Django’s support for inter-service communication, combined with its established ecosystem, makes it a solid choice for building complex distributed systems.</p><h3><strong>Conclusion</strong></h3><p>Django’s secret power lies in its versatility beyond traditional web development. Its ability to handle command-line utilities, backend data processing, API development, task scheduling, and microservices showcases its adaptability to various software development contexts. Whether you’re building a command-line tool, processing large datasets, developing APIs for mobile applications, or implementing a distributed system, Django provides a reliable and efficient framework to support your endeavors. So, the next time you think of Django, remember its secret power and consider its potential beyond the web.</p><blockquote>Guys, please <strong>Follow </strong>me<strong> </strong>for more such articles! It motivates me to write more amazing stuff related to <strong>Python Django Stack</strong>.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef27bfd7ed97" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django Channels with Daphne, Gunicorn and Nginx on DigitalOcean : All In One Guide]]></title>
            <link>https://awstip.com/django-channels-with-daphne-gunicorn-and-nginx-on-digitalocean-all-in-one-guide-28625eead962?source=rss-857a55c5b646------2</link>
            <guid isPermaLink="false">https://medium.com/p/28625eead962</guid>
            <category><![CDATA[ubuntu-server]]></category>
            <category><![CDATA[hosting]]></category>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Saurabh]]></dc:creator>
            <pubDate>Thu, 11 Mar 2021 17:05:06 GMT</pubDate>
            <atom:updated>2023-07-14T14:22:55.536Z</atom:updated>
            <content:encoded><![CDATA[<h3>Django Channels with Daphne, Gunicorn and Nginx on AWS, Google Cloud, Azure, DigitalOcean: All In One Guide</h3><h4>Django, Django-Channels, PostgreSQL, Gunicorn, Daphne, Nginx, Websockets, Ubuntu Server, AWS, Google Cloud, Azure, Digital Ocean: All In One Guide</h4><h3>Introduction</h3><p>Django is an amazing and powerful web framework. It provides a simplified development server for testing our code on local host but for the production level there must be a more secure, powerful and fast server. This is a kind of ALL IN ONE guide. We will demonstrate Ubuntu user setup, installation of required packages such as Python, PostgreSQL and their dependencies. We will setup a PostgreSQL database for this project. We will configure the Gunicorn application server to serve simple HTTP/HTTPS requests and will configure Daphne application server to serve web socket WS/WSS requests. We will then set up Nginx to reverse proxy to Gunicorn, giving us access to its security and performance features to serve our application.</p><blockquote><strong>Note:</strong> In this guide we will create a Ubuntu User <strong>saurabh</strong> and our django project name will be <strong>djangoproject<em>.</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*grQtRddJZ6pLErj2yeRYPA.png" /></figure><h3>Prerequisites and Goals</h3><p>In order to follow this guide, you all need a fresh Ubuntu Server instance with root user and basic knowledge of Ubuntu. Then we will create a non-root user <strong><em>saurabh</em></strong> with sudo privileges. We will be installing Django within a virtual environment. Once we have our database and application up and running, we will install and configure the Gunicorn and Daphne application server. This will serve as an interface to our application, translating client requests in HTTP or WS to our application. We will then set up Nginx in front of Gunicorn and Daphne to take advantage of its high performance connection handling mechanisms with more security features.</p><p><strong>Let’s Get Started !</strong></p><h3>Installation of Required Packages on our Ubuntu Server</h3><h4>Login to Ubuntu Server via SSH</h4><p>To access your remote server, Open terminal or cmd on your local system and simply paste it and hit enter.</p><p>ssh root@&lt;server IP address&gt;</p><p>Now enter your server’s <strong><em>root</em></strong> password and that’s it!</p><h3>Ubuntu User Creation</h3><p>Once you are logged in as root, we’re going to add the new user account that we will use to log in from now on. In order to add a user <strong><em>saurabh</em></strong> simply type:</p><p># adduser saurabh</p><p>Now let’s grant root privileges to newly created user <strong><em>saurabh</em></strong> by typing:</p><p># usermod -aG sudo saurabh</p><h4>Installation of Server Dependencies</h4><p>In this section we will be installing some required packages such as <strong><em>Python</em></strong>, <strong><em>Postgresql</em></strong>, <strong><em>Nginx</em></strong> from the Ubuntu Repositories. Firstly we need to update the local <strong><em>apt</em></strong> package index and then download and install these dependencies.</p><p>sudo apt-get update</p><p>and then if you are using <strong><em>Python 2</em></strong>, enter:</p><p>sudo apt-get install python-pip python-dev libpq-dev postgresql postgresql-contrib nginx</p><p>And for <strong><em>Python 3</em></strong>, enter:</p><p>sudo apt-get install python3-pip python3-dev libpq-dev postgresql postgresql-contrib nginx</p><h4>Setup of PostgreSQL Database and User</h4><p>Let’s create a Postgresql database and a database user for our Django web application. Login to Postgres console by typing:</p><p>sudo -u postgres psql</p><p>Now let’s create a database first, with name <strong><em>djangoprojectdb</em></strong>:</p><p>postgres=# CREATE DATABASE djangoprojectdb;</p><p>Create a database user (<strong><em>djangoprojectuse</em></strong>r) with password <strong><em>mypassword123</em></strong> by typing:</p><p>postgres=# CREATE USER djangoprojectuser WITH PASSWORD &#39;mypassword123&#39;;</p><p>By default Django uses UTF-8 encoding, hence we are setting default encoding to UTF-8 and timezone to UTC and default transaction isolation scheme to “read committed”.</p><p>postgres=# ALTER ROLE djangoprojectuser SET client_encoding TO &#39;utf-8&#39;;</p><p>postgres=# ALTER ROLE djangoprojectuser SET default_transaction_isolation TO &#39;read committed&#39;;</p><p>postgres=# ALTER ROLE djangoprojectuser SET timezone TO &#39;UTC&#39;;</p><p>And lastly grant permissions to our newly created database user <strong><em>djangoprojectuser </em></strong>on database <strong><em>djangoprojectdb</em></strong></p><p>postgres=# GRANT ALL PRIVILEGES ON DATABASE djangoprojectdb TO djangoprojectuser;</p><p>Now exit out from the <strong><em>Postgresql</em></strong> prompt bt typing:</p><p>postgres=# \q</p><h4>Python Virtual Environment Setup</h4><p>Let’s create our python virtual environment for our project. First we need to upgrade pip and install <strong><em>virtualenv</em></strong> package. If you are using <strong><em>Python 2</em></strong>, use:</p><p>sudo -H pip install --upgrade pip</p><p>sudo -H pip install virtualenv</p><p>and for <strong><em>Python 3</em></strong>, use:</p><p>sudo -H pip3 install --upgrade pip</p><p>sudo -H pip3 install virtualenv</p><p>Now we can setup our project files. First we need to create a folder for our project with name <strong><em>djangoproject </em></strong>and<strong><em> </em></strong>navigate to this folder:</p><p>mkdir ~/djangoproject</p><p>cd ~/djangoproject</p><p>In this project directory, create a Python Virtual Environment with name <strong><em>env</em></strong> by typing:</p><p>virtualenv env</p><p>Now we need to activate our virtual environment <strong><em>env</em></strong>, so that we can install our project dependencies.</p><p>source env/bin/activate</p><p>Your prompt should change to indicate that you are now operating within a Python virtual environment. It will look something like this:</p><p>(env)user@host:~/djangoproject$</p><p>As we are using PostgreSQL Database and django, install dependencies:</p><p>(env) $ pip install django gunicorn psycopg2-binary</p><h4>Bring your Django Project to the Picture</h4><p>Now we need to create our Django project or we can simply pull a project from our existing git repository. Let’s create a fresh project <strong><em>djangoproject</em></strong> within our djangoproject directory.</p><p>(env) $ django-admin startproject djangoproject</p><p>Now add your server IP or domain name to <strong>ALLOWED_HOSTS</strong> in settings.py file of our djangoproject. We can edit any file on the terminal by using any text editor like nano, vim etc. Navigate to project base directory and to edit <strong><em>settings.py</em></strong> file simply enter:</p><p>(env) $ sudo nano settings.py</p><p>After adding our domain or IP to <strong>ALLOWED_HOSTS</strong> we need to setup our django databse, we will simply add this config to settings.py:</p><pre>DATABASES = {    <br>   &#39;default&#39;: {        <br>       &#39;ENGINE&#39;: &#39;django.db.backends.postgresql_psycopg2&#39;,        <br>       &#39;NAME&#39;: &#39;djangoprojectdb&#39;,        <br>       &#39;USER&#39;: &#39;djangoprojectuser&#39;,        <br>       &#39;PASSWORD&#39;: &#39;mypassword123&#39;,        <br>       &#39;HOST&#39;: &#39;localhost&#39;,        <br>       &#39;PORT&#39;: &#39;&#39;,    <br>    }<br>}</pre><p>Now we need to configure our static and media files so that nginx can also serve them, our configuration will look similar to this:</p><pre>STATIC_URL = &#39;/static/&#39;<br>STATIC_ROOT = os.path.join(BASE_DIR, &quot;static&quot;)<br>MEDIA_URL=&#39;/media/&#39;<br>MEDIA_ROOT = os.path.join(BASE_DIR, &quot;media&quot;)</pre><p>To save changes press <strong>CTRL+X</strong> and enter <strong>y</strong> and press <strong>ENTER</strong>.</p><p>Now, we can migrate the initial database schema to our PostgreSQL database and collect project static files using the management script:</p><pre>python manage.py makemigrations<br>python manage.py migrate<br>python manage.py collectstatic</pre><p>UFW firewall is protecting your server. In order to test the development server, we’ll have to allow access to the port we’ll be using.</p><p>Create an exception for port 8000 by typing:</p><p>(env) $ sudo ufw allow 8000</p><p>Finally, we can test our project by starting up the development server with this command:</p><p>(env) $ python manage.py runserver 0.0.0.0:8000</p><p>Now in your browser visit your server’s domain name or IP address followed by :8000</p><blockquote><a href="http://server_domain_or_ip:8000/">http://server_domain_or_IP:8000</a></blockquote><p>You should see your project’s index page.</p><h3>Create a Gunicorn systemd Service</h3><p>Firstly we want to test Gunicorn to make sure that it can serve the application. We can do this by entering our project directory and using gunicorn to load the project’s WSGI module:</p><p>(env) $ gunicorn --bind 0.0.0.0:8000 djangoproject.wsgi</p><p>This will start Gunicorn on the same interface that the Django development server was running on. You can go back and test the app again. Now press <strong>CTRL+C</strong> in the terminal to stop gunicorn and let’s exit from virtual environment too by typing:</p><p>(env) $ deactivate</p><p>We have tested that Gunicorn can interact with our Django application, but we should implement a more robust way of starting and stopping the application server. To accomplish this, we’ll make a systemd service file.</p><p>Let’s create and open a systemd service file for Gunicorn in nano text editor:</p><p>sudo nano /etc/systemd/system/gunicorn.service</p><p>And our <strong><em>gunicorn.service</em></strong> file will look similar to this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c33addaa81e42db196ce94fa6867dd5/href">https://medium.com/media/7c33addaa81e42db196ce94fa6867dd5/href</a></iframe><blockquote><strong>Note:</strong> In our <strong><em>gunicorn.service</em></strong> file we set the path for <strong><em>djangoproject.sock</em></strong> file in <strong><em>saurabh</em></strong> directory (outside of our base directory <strong><em>/home/saurabh/djangoproject.sock</em></strong>) instead of our project <strong><em>base</em></strong> directory (<strong><em>/home/saurabh/djangoproject/djangoproject.sock</em></strong>) because if we put this file in project base directory this file will be <strong>removed</strong> <strong>in every git pull operation</strong> and we have to create it every time or we have to include it in our git project repository. That’s why we put this file outside our project’s base directory.</blockquote><p>Save and close it now. We can now start the Gunicorn service we created and enable it so that it starts at boot:</p><pre>sudo systemctl start gunicorn<br>sudo systemctl enable gunicorn</pre><p>Check the status of the process to find out whether it was able to start:</p><p>sudo systemctl status gunicorn</p><p>Next, check for the existence of the <strong><em>djangoproject.sock</em></strong> file within your home directory:</p><p>ls /home/saurabh</p><p>In output you will see <strong><em>djangoproject.sock</em></strong> file.</p><pre>OUTPUT:<br>djangoproject djangoproject.sock</pre><p>If you don’t find <strong><em>djangoproject.sock</em></strong> file or there is an error in response of <strong><em>systemctl status</em></strong> command, this indicates that gunicorn didn’t start correctly. To check the gunicorn logs simply type:</p><p>sudo journalctl -u gunicorn</p><p>Whenever you make any changes to <strong><em>/etc/systemd/system/gunicorn.service</em></strong> file, don’t forget to reload the <strong><em>daemon</em></strong> and restart the <strong><em>gunicorn</em></strong> by typing:</p><pre>sudo systemctl daemon-reload<br>sudo systemctl restart gunicorn</pre><h4>Nginx Configuration</h4><p>Now after the successful set up of Gunicorn, we need to configure Nginx to pass traffic to the process. Let’s create a new server block in Nginx’s sites-available folder by typing:</p><p>sudo nano /etc/nginx/sites-available/djangoproject</p><p>In this configuration file we need to specify some important things such as port numbers for websocket: 8001 and HTTP: 80 requests, server name or IP address, locations of our project’s static and media files and required configurations for websocket connections so that Nginx can redirect websocket requests WS or WSS to <strong><em>Daphne </em></strong>and simple HTTP or HTTPS requests to <strong><em>Gunicorn.</em></strong></p><p>And final <strong><em>Nginx</em></strong> configurations will look similar to this:</p><pre>upstream channels-backend {<br> server localhost:8001;<br>}</pre><pre>server {</pre><pre>    listen 80;<br>    server_name server_domain_or_IP;</pre><pre>    location = /favicon.ico { access_log off; log_not_found off; }<br>    location /static/ {<br>        root /home/saurabh/djangoproject;<br>    }<br>    location /media/ {<br>        root /home/saurabh/djangoproject;<br>    }</pre><pre>location / {<br>        include proxy_params;<br>        proxy_pass <a href="http://unix/home/niom/niompmo.sock">http://unix:/home/saurabh/djangoproject.sock</a>;<br>    }</pre><pre>location /ws/ {<br>        proxy_http_version 1.1;<br>        proxy_set_header Upgrade $http_upgrade;<br>        proxy_set_header Connection &quot;upgrade&quot;;<br>        proxy_redirect off;<br>        proxy_pass <a href="http://127.0.0.1:8001/">http://127.0.0.1:8001</a>;<br>        proxy_set_header Host $host;<br>        proxy_set_header X-Real-IP $remote_addr;<br>        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;<br>        proxy_set_header X-Forwarded-Host $server_name;</pre><pre>    }</pre><pre>}</pre><blockquote><strong><em>Note:</em></strong> On Digital Ocean server we don’t need to specify full path to our project’s static and media directories because it automatically appends static and media to the static and media locations respectively. That’s why we wrote <strong><em>/home/saurabh/djangoproject</em></strong> instead of <strong><em>/home/saurabh/djangoproject/media OR static </em></strong>in our nginx config file.</blockquote><p>Save and close the config file enable the file by linking it to the sites-enabled directory:</p><p>sudo ln -s /etc/nginx/sites-available/djangoproject /etc/nginx/sites-enabled</p><p>Above command will create a <strong><em>symlink</em></strong> in sites-enable directory for Nginx config file in sites-available directory. Now test your Nginx configuration for syntax errors by typing:</p><p>sudo nginx -t</p><p>If everything is fine then restart Nginx by typing:</p><p>sudo systemctl restart nginx</p><p>Now update these firewall rules and allow full access to Nginx:</p><pre>sudo ufw delete allow 8000<br>sudo ufw allow &#39;Nginx Full&#39;</pre><h4>Redis Setup for Django Channels</h4><p>Redis is used to store messages temporarily for django channels. Install Redis by typing:</p><p>sudo apt install redis-server</p><p>Now edit redis.conf by typing:</p><p>sudo nano /etc/redis/redis.conf</p><p>Inside the file, find the <strong><em>supervised</em></strong> directive. This directive allows you to declare an init system to manage Redis as a service, providing you with more control over its operation. The <strong><em>supervised</em></strong> directive is set to <strong><em>no</em></strong> by default. Since you are running Ubuntu, which uses the systemd init system, change this to <strong><em>systemd</em></strong>:</p><pre># If you run Redis from upstart or systemd, Redis can interact with your<br># supervision tree. Options:<br>#   supervised no      - no supervision interaction<br>#   supervised upstart - signal upstart by putting Redis into SIGSTOP mode<br>#   supervised systemd - signal systemd by writing READY=1 to $NOTIFY_SOCKET<br>#   supervised auto    - detect upstart or systemd method based on<br>#                        UPSTART_JOB or NOTIFY_SOCKET environment variables<br># Note: these supervision methods only signal &quot;process is ready.&quot;<br>#       They do not enable continuous liveness pings back to your supervisor.</pre><pre><strong>supervised systemd</strong></pre><p>Now restart the redis service by:</p><p>sudo systemctl restart redis.service</p><p>Now check the status of redis by:</p><p>sudo systemctl status redis</p><p>and the output must be like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*OlIFpLnu6D-fsqhzkXKILA.png" /></figure><p>Now install net-tools and confirm that Redis is running at 127.0.0.1. and port should be <strong><em>6379</em></strong> by default and restart the Redis using the following commands:</p><pre>sudo apt install net-tools<br>sudo netstat -lnp | grep redis<br>sudo systemctl restart redis.service</pre><p>Now navigate to your project directory (where <strong><em>settings.py</em></strong> file resides) and create or update the existing <strong><em>asgi.py</em></strong> file according to this sample file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a73fb7ae4083bebca9ef3a459008c7d/href">https://medium.com/media/8a73fb7ae4083bebca9ef3a459008c7d/href</a></iframe><h4>Daphne Setup for Django Channels</h4><p><strong><em>Gunicorn</em></strong> is what we use to run the WSGI application — which is our django app. To run the ASGI application we need something else, an additional tool. <strong><em>Daphne</em></strong> was built for Django channels. Let’s install <strong><em>Daphne</em></strong> by:</p><p>sudo apt install daphne</p><p>Now we need to update the <strong><em>daphne.service</em></strong>, open it with nano editor by:</p><p>sudo nano /etc/systemd/system/daphne.service</p><p>Here we will be using port 8001 for our websocket connections and this file will be look similar to this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91dcb6ea56168d940a976348754f7605/href">https://medium.com/media/91dcb6ea56168d940a976348754f7605/href</a></iframe><p>Now let’s reload <strong><em>daemon</em></strong> and restart <strong><em>daphne.service</em></strong> by:</p><pre>systemctl daemon-reload<br>systemctl start daphne.service<br>systemctl status daphne.service</pre><p>You should see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*iCZL5lMaEbMV-iRl9GJZ1Q.png" /></figure><p>Now close it using <strong>CTRL+C</strong> and we need to start daphne using a <strong><em>systemd</em></strong> service when the server boots, just like we start gunicorn and then gunicorn starts the django application. For this purpose let’s create a <strong><em>daphneboot.sh</em></strong> file by typing:</p><p>sudo nano /root/daphneboot.sh</p><p>And paste the content:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d591ea4fded116fc64be9418327116e/href">https://medium.com/media/5d591ea4fded116fc64be9418327116e/href</a></iframe><p>Make this script executable by the following command:</p><p>chmod u+x /root/daphneboot.sh</p><p>Now we need to tell <strong><em>systemd</em></strong> to run the our <strong><em>daphneboot.sh</em></strong> script when the server boots. For this purpose we have to create a systemd service and to create this service, simply paste:</p><p>sudo nano /etc/systemd/system/daphneservice.service</p><p>And paste the content:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac067f37fb0a1b3930cb29e1c1358886/href">https://medium.com/media/ac067f37fb0a1b3930cb29e1c1358886/href</a></iframe><p>Now reload the <strong><em>daemon</em></strong>; <strong><em>start</em></strong> and <strong><em>enable</em></strong> our newly created <strong><em>daphneservice.service</em></strong> and allow access to the port 8001 by typing:</p><pre>systemctl daemon-reload<br>sudo systemctl start daphneservice<br>sudo systemctl enable daphneservice<br>ufw allow 8001</pre><p>And restart the server by:</p><p>sudo shutdown -r now</p><p>Now log on to the server again and check the status of our <strong><em>daphneservice.service</em></strong> and <strong><em>daphne.service</em></strong> by:</p><pre>systemctl status daphneservice.service<br>systemctl status daphne.service</pre><p>If everything is fine then you can see websocket working properly on the server. Further you can add domain name to your ubuntu server and can install SSL certificates so that your server can serve HTTPS and WSS requests as well. You can install SSL certificates python-certbot package (To install python-certbot for Nginx simply enter: <strong>sudo apt install certbot python3-certbot-nginx</strong>). And then run this command to generate SSL certificates:</p><pre>sudo certbot --nginx -d &lt;your-domain-name.com&gt; -d www.&lt;domain-name.com&gt;</pre><p>Then you can also set a timer to auto renew your SSL certificates by typing:</p><pre>sudo systemctl status certbot.timer<br>sudo certbot renew --dry-run</pre><h4>Nginx Server Error Logs</h4><p>You can check your Nginx server’s error logs by typing:</p><pre>sudo tail -F /var/log/nginx/error.log</pre><h3>Conclusion</h3><p>Hence, in this guide we setup our Django server in this way that it can serve both HTTP and WS requests. Nginx will redirect all HTTP requests to the Gunicorn and all WS requests to Daphne. And then respective server will serve these client requests accordingly. Still, you have a query regarding Django Hosting Tutorial, please leave comments below.</p><blockquote>Guys, please <strong>Follow </strong>me<strong> </strong>for more such articles! It motivates me to write more amazing stuff related to <strong>Python Django Stack</strong>.</blockquote><p>Thank you :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28625eead962" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/django-channels-with-daphne-gunicorn-and-nginx-on-digitalocean-all-in-one-guide-28625eead962">Django Channels with Daphne, Gunicorn and Nginx on DigitalOcean : All In One Guide</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>