如何在Django temp中执行增量运算符

2024-04-30 06:21:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试获取聊天中未读消息的数量,它在django shell中运行良好,但我在模板中遇到了问题,因为我不能使用增量运算符

在django shell中,我使用了以下代码

# After importing the required models
unread = 0 
for message in chat.messages.all():
    if message.read != True:
       unread += 1

这个很好用

在模板中,我使用了下面的代码

{%for message in chat.messages.all %} 
             {% with unread=0 %}  
             {% if message.read != True %} 
                  {{unread+=1}}
             {% endif %}
             {% endwith %}
     <span class="badge badge-light badge" style="margin-top: 27px; font-size: 2.5em; float:right; border-radius: 1.0rem;">{{unread}}</span>

{%endfor%}

我希望能够像在django shell中一样输出未读消息的数量


Tags: django代码inbadge模板消息messagefor
1条回答
网友
1楼 · 发布于 2024-04-30 06:21:17

你不需要增加。只需计算视图中未读的消息并将其传递给模板。模板中不需要for循环。你知道吗

查看

unread = chat.messages.filter(read=False).count()

模板

<span ...>{{ unread }}</span>

相关问题 更多 >