ITZone

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

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:

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

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.

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.

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