一旦“读取”,通知将不可点击:错误“未定义notification_id”

时间:2019-05-03 14:15:31

标签: javascript python jquery django django-views

我正在将JQuery / JS与Django Channels WebSockets一起使用,以配置聊天消息的实时通知。

当用户具有Notificationnofication_read=False对象时,它们将通过以下代码在导航栏中显示。

{{ notification|length }}显示带有Notification的{​​{1}}个对象的数量。

navbar.html

nofication_read=False

我知道目前这不是实时的。

但是问题是,当用户刷新页面并单击红色图标<li id="notification_li" class="nav-item"> <a class="nav-link" href="#" id="notificationLink"> <span id="notification_id{{notification_id}}">{{ notification|length }}</span> <div id="notificationContainer"> <div id="notificationTitle">Notifications</div> <div id="notificationsBody" class="notifications"> {% for notifications in notification|slice:"0:10" %} <span id="notification-{{notification.id}}"> {{ notifications.notification_chat.message }} via {{ notifications.notification_chat.user }} at {{ notifications.notification_chat.timestamp }} </span> {% endfor %} 以显示其未读通知列表时,数据通过网络套接字(span id=notification_id)发送为{{ 1}}会在JSON.stringify中调用"type": "notification_read"命令,从而在数据库中将其标记为if message_type == "notification_read":

当用户刷新页面时,红色图标不再存在,并且当他们尝试单击背景链接时,由于浏览器控制台中的错误,该图标不可点击

consumers.y

他们再次收到通知并刷新页面后,显然可以再次单击该页面。

首次点击后,用户仍然应该能够点击并查看nofication_read=True通知列表。

consumers.py

Uncaught ReferenceError: notification_id is not defined

context_processors.py

read

base.html

class ChatConsumer(AsyncConsumer):
    ...
    async def websocket_receive(self, event):
        message_type = json.loads(event.get('text','{}')).get('type')
        if message_type == "notification_read":
            user = self.scope['user']
            username = user.username if user.is_authenticated else 'default'
            # Update the notification read status flag in Notification model.
            notification = Notification.objects.filter(notification_user=user).update(notification_read=True)
            print("notification read")
            return 

front_text = event.get('text', None)
        if front_text is not None:
            loaded_dict_data = json.loads(front_text)
            msg =  loaded_dict_data.get('message')
            user = self.scope['user']
            username = user.username if user.is_authenticated else 'default'
            notification_id = 'default'
            myResponse = {
                'message': msg,
                'username': username,
                'notification': notification_id,
            }
   ...
        await self.create_chat_message(user, msg)
        other_user = self.scope['url_route']['kwargs']['username']
        other_user = User.objects.get(username=other_user)
        await self.create_notification(other_user, msg)
       ...
@database_sync_to_async
def create_chat_message(self, me, msg):
    thread_obj = self.thread_obj
    return ChatMessage.objects.create(thread=thread_obj, user=me, message=msg)

@database_sync_to_async
def create_notification(self, other_user, msg):
    last_chat = ChatMessage.objects.latest('id')
    created_notification = Notification.objects.create(notification_user=other_user, notification_chat=last_chat)
    return created_notification

1 个答案:

答案 0 :(得分:2)

"notification_id": notification_id之前,您应该定义notification_id,但是如果您需要循环执行,可以尝试:

 $("#notificationLink").click(function() {

   $('span[id^="notification-"]').each(function(){
        var notification_id = $(this).attr('id').substring(13)
        var data = {
          "type": "notification_read",
          "username": username,
          "notification_id": notification_id,
        }
        socket.send(JSON.stringify(data));
    });

    $("#notificationContainer").fadeToggle(300);
    $("#notification_id").fadeOut("slow");
    return false;
  })

我希望您的模板中已经有以下内容:

var username = '{{ request.user.username }}'

根据您当前在后端的代码,您不需要notification_id,因此您可以简单地将其删除:

 $("#notificationLink").click(function() {
    var data = {
      "type": "notification_read",
      "username": username,
    }
    socket.send(JSON.stringify(data));

    $("#notificationContainer").fadeToggle(300);
    $("#notification_id").fadeOut("slow");
    return false;
  });