Django Channels “For example, updating the user’s online real-time status online

Tram Ho

In this article, I will do a simple example of using Channels in Django to create users’ online-offline status real-time updates.

1. Installation and configuration

Download the project directory

In this article, I will use myproject / project directory which you can download by:

Activate the virtual environment and run migrate

Conduct installation of Channels in virtual environment

settings

Edit the settings.py file to add Channels and Projects

routing

2. Create Accounts application

We will create an application named accounts.

Our project structure will be as follows:

views

At the file views.py of the accounts / directory specified as follows:

URL

Create a file urls.py at the accounts directory / to determine the url link to the views.

In the file urls.py of the mypoject / project directory we edit to link to the above url as follows:

Template

Create new_user.html file to determine the template. ‘

Now open the browser on http://127.0.0.1:8000 to look like this:

React / Redux Study via practical examples: Connect with SoundCloud
Compare predictive models in face recognition problems and practical examples

3. Consumers

We now determine our consumers.
Create an consumers.py file in the accounts / directory as follows:

Consumer helps communicate handling events, and sends messages back to the browser.

There are several subclasses of consumers you can use in addition to AsyncConsumer and SyncConsumer like:

  • WebsocketConsumer and AsyncWebsocketConsumer
  • JsonWebsocketConsumer and AsyncJsonWebsocketConsumer
  • AsyncHttpConsumer

And here I use AsyncJsonWebsocketConsumer to actually transmit and receive via JSON encryption. It has properties like:

  • connect (): Execute when the Consumer is connected.
  • receive_json (): Executes when a message is received through the send method of WebSocket
  • disconnect (): Executes when a consumer disconnects
  • accept () Use accept () to accept WebSocket connection, if not call this method in connect (), it will reject WebSocket and will be closed.
  • channel_layer (), channel_name (): Each consumer when the connection is automatically added to the channel_layer () and channel_name () attributes. When a request comes to us, there will be channel_name ().
  • Group: We will use group_add to add this channel_name () to the group named “users”, and group_discard to remove this channel_name () from the group when the user exits or this consumer closes.

4. WebSocket

Now we will create WebSocket to communicate with Consumers. Edit the new_user.html file as follows

In the first file we use reconnecting-websocket.min.js download at reconnecting-websocket. I will explain why use it later. Create a new_user.js file in the site_static / js / channels / directory as follows: site_static / channels / new_user.js

  1. First, we will connect WebSocket to the path ws: //127.0.0.1: 8000 / new-user / where we previously defined the router as path (“new-user /”, NewUserConsumer).

These two must match for example if the router is path (“new-user-update /”, NewUserConsumer), the path must be ws: //127.0.0.1: 8000 / new-user-update /

  1. As mentioned above, here you can use as var socket = new WebSocket (endpoint). However, using ReconnectingWebSocket will make WebSocket automatically reconnect when WebSocket is closed. When it is onclose, it will automatically turn onopen.
  2. Methods onopen, onclose, onmessage to determine WebSocket status to connect, close and receive messages. Use console.log to make it easier to check errors.

5. Templates

Now everything is ready, but we haven’t done anything yet. The task here is to automatically update the online-offline status of the user. Add the new_user.html file as follows: templates / new_user.html

Create a users.html file in the templates / includes / directory as follows:

Opening the browser at http://127.0.0.1:8000/ will look like this:

There is no information because we have not created any users yet. You add yourself some users at the admin page. After adding 3 users it will look like this:

6. Update status

models

To know the status of online or offline we need to add a status field for the User model. By locating the Profile model and connecting OneToOne to the User as follows: accocunts / models.py

Default will let False be the Offline status

Running migration:

Consumers

Now go to the most important part, edit the consumers to check the online-offline state.

  • When the user is online: Consumer is in connect state -> update status = True -> update the page.
  • When the offline user: Cusumer is disconnected -> update status = False -> update the page. Customize the consumer as follows:

accounts / consumers.py

  1. Because it is not possible to use the synchronous code asynchronously together. So here we use database_sync_to_async provided by Channels to allow us to access the database and edit the Profile.
  2. The update_user_status () method will be responsible for updating the status of the user.
  3. The send_status () method uses send_json to send information to Websocket as JSON code. The Websocket side will receive information at the onmessage method with the data name.
  4. Using the group_send method includes 2 arguments. The first argument is the group name as “users”, the second argument contains the information to be sent.
  • type: Specifies the method name to be executed in the consumer. This means that each time you call group_send (), it will execute the method that the type determines.
  • html_users: This is the HTML code that contains user information that has been updated to the status. It will be used to replace the old html code with Jquery to update the status.

Websocket

Now WebSocket can receive messages in onmessage. Now we need to deal with that information. Correct the new_user.js file in the site_static / js / channels / directory as follows

As mentioned, the information received from consumers sent to Websocket is JSON code with the name data. So here we need to use JSON method in JS to read it. With the information received, we will replace the HTML code at the tag with the new_user id of new_user.html with Jquery.

Achievement

So we are done with the task of updating real-time online status – offline of the user. The result may look like this:

Just a little more

Every time we log out we have to go to admin to do it. That’s a little troublesome during the test. We will add the logout logon button as follows

URL

Edit the urls.py file of the accounts / directory as follows:

Here I use Django’s available application at django.contrib.auth to perform the login and logout process.

templates

Create registration / directory at templates / directory. In this directory, create 2 files, login.html and logged_out.html. These two files are the files that the auth application will point to.

log in

templates / registration / login.html

Log out

templates / registration / logged_out.html

navbar

Add the navbar with the login and logout buttons as follows: templates / base.html

In includes folder / create navbar.html file as follows:

setting

Add the setting file as follows:

Here will determine the URL for the login, logout, and redirect page after successful login.

Result

Some basic differences between Vue and React are through a simple example
Learn UX by example – designing a registration screen (Sign up-form)
Share the news now

Source : viblo