get_messages(request)
[source]
In your template, use something like:
{% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %}
If you’re using the context processor, your template should be rendered with a RequestContext
. Otherwise, ensure messages
is available to the template context.
Even if you know there is only just one message, you should still iterate over the messages
sequence, because otherwise the message storage will not be cleared for the next request.
The context processor also provides a DEFAULT_MESSAGE_LEVELS
variable which is a mapping of the message level names to their numeric value:
{% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}> {% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}Important: {% endif %} {{ message }} </li> {% endfor %} </ul> {% endif %}
Outside of templates, you can use get_messages()
:
from django.contrib.messages import get_messages storage = get_messages(request) for message in storage: do_something_with_the_message(message)
For instance, you can fetch all the messages to return them in a JSONResponseMixin instead of a TemplateResponseMixin
.
get_messages()
will return an instance of the configured storage backend.
Please login to continue.