导航栏通知的Django模板语言语法 [英] Django templating language syntax for navbar notifications

查看:56
本文介绍了导航栏通知的Django模板语言语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在我的 Django Channels 2.1.2 项目中使用Django模板语言,以在Facebook样式的通知弹出窗口中呈现所有未读的聊天消息。



未读聊天消息的列表(在各自的线程中)因为我在使用正确的语法时遇到问题而没有显示。



这是前端的外观。当您单击消息图标时,通知消失。





我有通知模型

  class Notification(models.Model):
notification_user = models.ForeignKey(User,on_delete = models.CASCADE)
notification_chat = models.ForeignKey(ChatMessage,on_delete = models.CASCADE)
notification_read = models.BooleanField(default = False)

def __str __(self):
return f'{self.id}'

navbar.html

  {%如果user.is_authenticated %} 
< li id = notification_li class = nav-item>
< a class = nav-link href =# id = notificationLink>
< i class = fas fa-envelope< / i>& nbsp;收件箱/ a
{通知中的通知%的百分比}
< span id = notification_id> {{notifications.notification_chat}}< / span>
{%endfor%}
< div id = notificationContainer>
< div id = notificationTitle> Notifications< / div>
< div id = notificationsBody class = notifications>
{{notification.notification_chatessage ?? }}
< / div>
< div id = notificationFooter>< a href = {%url‘chat:inbox’%}>查看全部< / a>< / div>
< / div>
< / li>

base.html

 < script> 
$(document).ready(function(){
$(#notificationLink)。click(function(){
$(#notificationContainer)。fadeToggle(300);
$(#notification_id)。fadeOut( slow);
return false;
});

//文档单击隐藏弹出窗口
$(document).click(function(){
$(#notificationContainer)。hide();
});

//点击弹出的
$(#notificationContainer)。click(function(){
return false;
});
});
< / script>

context_processors.py

  def通知(request):
如果request.user.is_authenticated:
通知= Notification.objects.filter(notification_user = request.user)
return {'notification' :notification}
返回Notification.objects.none()

我也有上下文处理器在正确的位置添加到设置
中。 notification_id 应该使用消息WebSocket发送,并在每次发送新消息时进行更新(我仍然无法成功完成此操作)。



consumers.py

  async def websocket_receive(self,event):
#当从网络套接字接收到一条消息时
print( receive,event)

message_type = event.get('type',None)#检查消息类型,采取相应措施
如果message_type == notification_read:
#更新Notification模型中的通知读取状态标志。
通知= Notification.object.get(id = notification_id)
notification.notification_read =真
notification.save()#提交到数据库
print( notification read)

front_text = event.get('text',None)
如果front_text不为None:
loaded_dict_data = json.loads(front_text)
msg = loaded_dict_data.get ('消息')
用户= self.scope ['user']
用户名='默认'
如果user.is_authenticated:
用户名= user.username
myResponse = {
'message':msg,
'username':用户名,
'notification':notification_id#发送通知
的唯一标识符}
。 ..

thread.html

  ... 
//下面是我收到
的消息socket.onmessage = function(e){
var data = JSON.parse(event.data);
//找到通知图标/按钮/任何
//并显示一个红点,然后将Notification_id作为id或data属性添加到元素。
console.log( message,e)
var chatDataMsg = JSON.parse(e.data)
chatHolder.append('< li>'+ chatDataMsg.message +'来自'+ chatDataMsg.username +'< / li>')
}

为了帮助我解决这个问题,我将非常感谢您提供的良好学习资源。

解决方案

要引用通知消息,您应该使用 {{notifications.notification_chat.message}} 。另外,要显示所有通知,您将必须遍历所有通知。


navbar.html




  {%如果user.is_authenticated%} 
< li id = notification_li class = nav-item >
< a class = nav-link href =# id = notificationLink>
< i class = fas fa-envelope< / i>& nbsp;收件箱/ a
{通知中的通知%的百分比}

< span id = inbox-{{notifications.id}}> {{notifications.notification_chat.message}}}< /跨度>

{%endfor%}
< div id = notificationContainer>
< div id = notificationTitle> Notifications< / div>
< div id = notificationsBody class = notifications>
{通知中通知的百分比%}

< span id = notification-{{notifications.id}}> {{notifications.notification_chat.message}}}< /跨度>

{%endfor%}
< / div>
< div id = notificationFooter>< a href = {%url‘chat:inbox’%}>查看全部< / a>< / div>
< / div>
< / li>

我还注意到在您的 thread.html ,当您从服务器获得响应时,您不会更新通知。您可以使用ID来添加新通知。


I am trying to use the Django templating language in my Django Channels 2.1.2 project to render out any unread chat messages in a Facebook-style notification popup.

The list of unread chatmessages (in their respective threads) are not displaying because I am having trouble with the correct syntax.

This is how the front end looks. When you click the message icon, the notification disappears.

I have a Notification model

class Notification(models.Model):
    notification_user = models.ForeignKey(User, on_delete=models.CASCADE)
    notification_chat = models.ForeignKey(ChatMessage, on_delete=models.CASCADE)
    notification_read = models.BooleanField(default=False)

    def __str__(self):
        return f'{self.id}'

navbar.html

 {% if user.is_authenticated %}
  <li id="notification_li" class="nav-item">
    <a class="nav-link" href="#" id="notificationLink">
      <i class="fas fa-envelope"></i>&nbsp; Inbox</a>
      {% for notifications in notification %}
      <span id="notification_id">{{ notifications.notification_chat }}</span>
      {% endfor %}
      <div id="notificationContainer">
            <div id="notificationTitle">Notifications</div>
            <div id="notificationsBody" class="notifications">
            {{ notification.notification_chatessage?? }}
            </div>
            <div id="notificationFooter"><a href="{% url 'chat:inbox' %}">See All</a></div>
      </div>
  </li>

base.html

  <script>
    $(document).ready(function() {
      $("#notificationLink").click(function() {
        $("#notificationContainer").fadeToggle(300);
        $("#notification_id").fadeOut("slow");
        return false;
      });

      //Document Click hiding the popup
      $(document).click(function() {
        $("#notificationContainer").hide();
      });

      //Popup on click
      $("#notificationContainer").click(function() {
        return false;
      });
    });
  </script>

context_processors.py

def notification(request):
    if request.user.is_authenticated:
        notification = Notification.objects.filter(notification_user=request.user)
        return {'notification':notification}
    return Notification.objects.none()

I have the context processor also added into settings in the correct place. The notification_id should be sent using the message WebSocket and updated each time a new message is sent (I still haven't managed to do this successfully).

consumers.py

async def websocket_receive(self, event):
        # when a message is received from the websocket
        print("receive", event)

        message_type = event.get('type', None)  #check message type, act accordingly
        if message_type == "notification_read":
             # Update the notification read status flag in Notification model.
             notification = Notification.object.get(id=notification_id)
             notification.notification_read = True
             notification.save()  #commit to DB
             print("notification read")

        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 = 'default'
            if user.is_authenticated:
                username = user.username
            myResponse = {
                'message': msg,
                'username': username,
                'notification': notification_id  # send a unique identifier for the notification
            }
            ...

thread.html

   ...
      // below is the message I am receiving
      socket.onmessage = function(e) {
        var data = JSON.parse(event.data);
        // Find the notification icon/button/whatever
        // and show a red dot, add the notification_id to element as id or data attribute.
        console.log("message", e)
        var chatDataMsg = JSON.parse(e.data)
        chatHolder.append('<li>' + chatDataMsg.message + ' from ' + chatDataMsg.username + '</li>')
      }

In addition to helping me with this question, I would really appreciate any good learning resources.

解决方案

For referencing the notification message, you should use {{notifications.notification_chat.message}}. Also, for showing all notifications, you will have to loop over all the notifications.

navbar.html

{% if user.is_authenticated %}
              <li id="notification_li" class="nav-item">
                <a class="nav-link" href="#" id="notificationLink">
                  <i class="fas fa-envelope"></i>&nbsp; Inbox</a>
                  {% for notifications in notification %}

                  <span id="inbox-{{notifications.id}}">{{ notifications.notification_chat.message }}</span>

                  {% endfor %}
                  <div id="notificationContainer">
                        <div id="notificationTitle">Notifications</div>
                        <div id="notificationsBody" class="notifications">
                        {% for notifications in notification %}

                            <span id="notification-{{notifications.id}}">{{ notifications.notification_chat.message }}</span>

                        {% endfor %}
                        </div>
                        <div id="notificationFooter"><a href="{% url 'chat:inbox' %}">See All</a></div>
                  </div>
              </li>

I also noticed that in your thread.html, you are not updating the notifications when you get a response from the server. you can use the ids to to prepend new notifications.

这篇关于导航栏通知的Django模板语言语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆