This is what I do using context processors:
project/application/context.py (check messages and add them to context):
def messages(request): messages = {} if 'message' in request.session: message_type = request.session.get('message_type', 'error') messages = {'message': request.session['message'], 'message_type': message_type} del request.session['message'] if 'message_type' in request.session: del request.session['message_type'] return messages
project/settings.py (add context to TEMPLATE_CONTEXT_PROCESSORS ):
TEMPLATE_CONTEXT_PROCESSORS = ( "django.core.context_processors.request", "django.core.context_processors.debug", "django.core.context_processors.media", "django.core.context_processors.auth", "project.application.context.messages", )
In this case, the messages function will be called upon each request and everything that it returns will be added to the template context. If necessary, if I want to give the user a message, I can do this:
def my_view(request): if someCondition: request.session['message'] = 'Some Error Message'
Finally, in the template, you can simply check if there are errors to display:
{% if message %} <div id="system_message" class="{{ message_type }}"> {{ message }} </div> {% endif %}
The type of message is used only in style, depending on what it is ("error", "notification", "success") and the configuration method, which you can add only 1 message at a time for the user, but thatβs all I really need needed so this works for me. It can be easily changed to allow multiple messages, etc.
Paolo bergantino
source share