Hisham Karam
Hisham Karam

Reputation: 1318

django channels not working how does it work i have read docs

iam trying to use channels but not working here is consumer.py

def ws_connect(message, cat_id):
    try:
        cat = Categories.objects.get(pk=cat_id)
    except Categories.DoesNotExist:
        pass
    Group('cat-1').add(message.reply_channel)


def ws_diconnect(message, cat_id):
    try:
        cat = Categories.objects.get(pk=cat_id)

    except Categories.DoesNotExist:
        pass
    Group('cat-1').discard(message.reply_channel)

and this is routing.py :

channel_routing = [
    route('websocket.receive', ws_connect, path=r'^/liveupdate/(?P<cat_id>\d+)/'),
    route("websocket.disconnect", ws_diconnect, path=r'^/liveupdate/(?P<cat_id>\d+)/'),
]

this is signals.py :

@receiver(post_save, sender=Tender)
def send_update(sender, instance, created, raw, using, **kwargs):
    print '>>>>>>>>>>>>>>>>>>>>>>>>>>>>', instance, '2', raw, '3', using, '4', kwargs
    data = json.dumps(
        {'ministry': 'hisham',})
    Group('cat-1').send({'tender': data,})
    print 'Done'

and here is javascript :

<script type="application/javascript">
    var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws";
    alert(ws_scheme +"://" + window.location.host + "/liveupdate/1/");
    var socket = new WebSocket(ws_scheme +"://" + window.location.host + "/liveupdate/1/");
    socket.onmessage = function(e) {
    alert(e.data);
};
    socket.onopen = function() {
        console.log("Connected to  socket");
    };
    socket.onclose = function() { console.log("Disconnected to  socket"); }

</script>

when iam tring to save tender signal fire but nothing in browser i.e no alert of data what is the wrong with my code any ideas

here is my folders: enter image description here

Upvotes: 0

Views: 552

Answers (1)

Anurag
Anurag

Reputation: 1013

Instead of websocket.receive use websocket.connect. Receive is used when client is sending data to server.

route('websocket.connect', ws_connect, path=r'^/liveupdate/(?P<cat_id>\d+)/'),

When are you sending data instead of tender use text as a Key.

Group('cat-1').send({'text': data,})

Upvotes: 2

Related Questions