0

I tried this approach stackoverflow but it didn't work

consumer.py

import json
import asyncio
from channels.consumer import AsyncConsumer
from django.contrib.auth import get_user_model
from channels.db import database_sync_to_async
from .models import Analytics

class AnalyticsConsumer(AsyncConsumer):
    async def websocket_connect(self, event):
        print('connected', event)
        await self.send({
            'type': 'websocket.accept'
        })
        analytics_obj = await self.getAnalytics()
        await self.send({
            'type': 'websocket.send',
            'text': str(analytics_obj)
        })

    async def websocket_receive(self, event):
        print('receive', event)


    async def websocket_disconnect(self, event):
        print('disconnected', event)

    @database_sync_to_async
    def getAnalytics(self):
        return list(Analytics.objects.all().values())[0]['number']

The console displays the message == analytics_obj but when I make changes in the database, it doesn't reflect in the console message. For that, I need to refresh the browser. What is the point in refreshing the browser when you are using WebSocket.

Meet Gondaliya
  • 387
  • 4
  • 18

1 Answers1

0

Just by updating a value in the db no new message is being sent to frontend. You need to send an "update" message over django channels after updating the database. So far the only time you send the analytics data is when you connect to the server.

hendrikschneider
  • 1,696
  • 1
  • 14
  • 26
  • So are you suggesting that I should define another async function like `async def updatedData(self, event)` ?? – Meet Gondaliya Jan 12 '22 at 04:05
  • Yes and the function needs to broadcast your update data. Check here for more info how to access the channels from outside the consumer: https://stackoverflow.com/questions/53461830/send-message-using-django-channels-from-outside-consumer-class/58372995#58372995 – hendrikschneider Jan 12 '22 at 07:37
  • Okay, thanks. your answer provided me with enough info to build a function to send the message to the client when received from outside the consumer class. I installed `websockets-client` and in `views.py` I sent the info needed to be displayed on the webpages via `websockets-client` library. But I couldn't use `django-channels` in `views.py`. For that I will follow your another suggestion, to access the channels outside of the consumer. – Meet Gondaliya Jan 12 '22 at 09:03