Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Building SPAs with Django and HTML Over the Wire

You're reading from  Building SPAs with Django and HTML Over the Wire

Product type Book
Published in Aug 2022
Publisher Packt
ISBN-13 9781803240190
Pages 264 pages
Edition 1st Edition
Languages
Author (1):
Andros Fenollosa Andros Fenollosa
Profile icon Andros Fenollosa

Table of Contents (14) Chapters

Preface 1. Part 1: Getting Started with Python
2. Chapter 1: Setting up the Virtual Environment 3. Chapter 2: Creating a Django Project around Docker 4. Part 2: WebSockets in Django
5. Chapter 3: Adding WebSockets to Django 6. Chapter 4: Working with the Database 7. Chapter 5: Separating Communication in Rooms 8. Part 3: HTML over WebSockets
9. Chapter 6: Creating SPAs on the Backends 10. Chapter 7: Creating a Real-Time Blog Using Only Django 11. Part 4: Simplifying the frontend with Stimulus
12. Chapter 8: Simplifying the Frontend 13. Other Books You May Enjoy

Chapter 5: Separating Communication in Rooms

Channels allow us to broadcast, send, and receive asynchronous messages to/from all clients that belong to a group. Within a group, we cannot filter a selection of users. To solve this problem and create a division or categories, we must resort to creating new Channels and manually grouping the clients.

So far, we can communicate with a customer who is isolated in a Channel or with all the customers connected to a common Channel. Now, it is time to learn how to control groups/Channels to separate and move customers between different groups as needed. You can even assign the same customer to several groups at the same time. For example, if we are creating a Chat, it would be useful for the user to be subscribed to a unique Channel to receive notifications, as well as another public group where all the customers can write freely, and other private groups where they can have conversations with other users. It makes sense for a client to...

Technical requirements

You can download the code for this chapter from this book’s GitHub repository: https://github.com/PacktPublishing/Building-SPAs-with-Django-and-HTML-Over-the-Wire/tree/main/chapter-5.

We will be using the template we constructed in Chapter 4, Working with the Database: https://github.com/PacktPublishing/Building-SPAs-with-Django-and-HTML-Over-the-Wire/tree/main/chapter-4/initial-template

I have changed the name of the application to Chat. Ensure that the App folder is called /app/chat/ and that apps.py has been renamed with its name variable:

from django.apps import AppConfig
 
class SimpleAppConfig(AppConfig):
    default_auto_field = "django.db.models.BigAutoField"
    name = "app.chat" # Update

If you rename an application, you must reflect this in /project_template/settings.py:

INSTALLED_APPS = [
    "channels",
    "django...

Basic functions for managing Channels

The basic functions for managing Channels are as follows:

  • send(): This is used to send new messages from the Consumer to a single client. We have used this function from the beginning of this book. However, we used the JsonWebsocketConsumer wrapper to make send_json() more convenient for sending JSON:
    data = {
                "my_data": "hi",
           }
    self.send_json(data)
  • group_send(): This is used to send new messages from the Consumer to a group of clients that we have previously defined. It is an asynchronous function, so we will need the whole Consumer to be asynchronous or, preferably, use the async_to_sync function. In the following example, you can see how the {"my_data": "hi"} JSON is sent to the whole group as "Main":
    from asgiref.sync import async_to_sync
    async_to_sync(self.channel_layer...

Creating a full Chat

A very popular exercise when implementing WebSockets in any technology is to create a simple Chat. However, the difficulty increases considerably when we have several connected clients who are going to talk in private spaces and open groups so that any client can read or participate. Using Channels, we are creating a solid enough abstraction so that we can focus on other issues.

Let’s create a Chat complete with modern features:

  • Message history
  • Private conversations
  • Groups
  • Customers associated with a registered user in the database

Next, we must define the database. We will define the models for users, rooms, and messages. That way, we will be able to store the actions of each user and there will be a record of everything that happens.

Defining the database

In this section, we are going to create some models in the database to manage customers, groups (which we will call rooms), and messages.

Edit /app/chat/models...

Summary

In this chapter, we created a functional chat with private rooms and groups, like other software such as Slack or Teams, with very few lines of JavaScript (no comments, less than 35 lines). In addition, we have taken the first steps in an authentication system. We can now register and manage clients in different Channels, depending on our needs, and know who is connected or disconnected. The magic is over – we are now masters of Channels.

In the next chapter, Chapter 6, Creating SPAs on the Backends, we will deal with the last few elements that are necessary to dynamize a site, such as changing pages, deciding when we want to update a whole section or add a new HTML fragment, working with sessions so as not to depend so much on the database, and validating the origin of the data to avoid cross-site request forgery (CSRF) with WebSockets. With all the skills we will have acquired, we will develop a complete SPA by building a blog in Chapter 7, Creating a Real-Time...

lock icon The rest of the chapter is locked
You have been reading a chapter from
Building SPAs with Django and HTML Over the Wire
Published in: Aug 2022 Publisher: Packt ISBN-13: 9781803240190
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}