messages.success(request, "Success. Your settings have been saved.")
Ok, so now in my template, I do this:
{% if messages %}
{% for m in messages %}
<div class="notification_message" data-message="{{ m }}">{{ m }}</div>
{% endfor %}
{% endif %}
But that's silly!!! I only have 1 message. I don't want it to loop through. How d开发者_StackOverflow中文版o I just display the top message? The most important message. Or, how do I display the success message?
As far as I know, there is no way to do this from within the template itself (without a custom tag or filter, of course). It's fairly easy to accomplish outside of the template though (untested):
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
Usage:
messages = get_messages(request)
the_last_message = last_message(messages)
the_last_success_message = last_message(messages, message_level.SUCCESS)
You can then pass these values into your template via the context.
精彩评论