开发者

In Django, how do I display the message (using Message Framework) without looping through?

开发者 https://www.devze.com 2023-01-28 07:24 出处:网络
messages.success(request, \"Success. Your settings have been saved.\") Ok, so now in my template, I do this:
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.

0

精彩评论

暂无评论...
验证码 换一张
取 消