This is what I do, using context processors:
project/application/context.py
(check for messages and add them to the 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 the context to the 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",
)
With the above the function messages
will be called on every request and whatever it returns will be added to the template's context. With this in place, if I want to give a user a message, I can do this:
def my_view(request):
if someCondition:
request.session['message'] = 'Some Error Message'
Finally, in a template you can just check if there are errors to display:
{% if message %}
<div id="system_message" class="{{ message_type }}">
{{ message }}
</div>
{% endif %}
The message type is just used to style depending on what it is ("error","notice","success") and the way that this is setup you can only add 1 message at a time for a user, but that is all I really ever need so it works for me. It could be easily changed to allow for multiple messages and such.