messages.success(request, "Success. Your settings have been saved.")
好的,现在在我的模板中,我这样做:
{% if messages %}
{% for m in messages %}
<div class="notification_message" data-message="{{ m }}">{{ m }}</div>
{% endfor %}
{% endif %}
但那太傻了!我只有1条消息。我不希望它循环。 我如何只显示热门消息?最重要的信息。 或者,如何显示成功消息?
答案 0 :(得分:0)
据我所知,模板本身无法做到这一点(当然没有自定义标签或过滤器)。虽然(未经测试),但在模板外完成相当容易:
from django.contrib.messages import get_messages, constants as message_level
def last_message(messages, level = None):
"""Returns the last Message object in the messages with the
specified level, or just the last message if no level is
specified
"""
if level is None:
return None if not messages else messages[-1]
level = int(level) # Not strictly necessary, but Message object does this in its __init__()
for message in reversed(messages):
if message.level == level:
return message
return None
用法:
messages = get_messages(request)
the_last_message = last_message(messages)
the_last_success_message = last_message(messages, message_level.SUCCESS)
然后,您可以通过上下文将这些值传递到模板中。