Messages notification in Django

Firstly, read the documentation carefully: https://docs.djangoproject.com/en/dev/ref/contrib/messages/
Following instructions in the documentation to enable messages framework and use it in your django application.

Example:

views.py:

...
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib import messages
from my_app import forms

def my_view(request):
    if request.method == 'POST':
        my_form = forms.MyForm(request.POST, request.FILES)
        if my_form.is_valid():
            my_form.save()
            messages.add_message(request, messages.INFO, "Success")
        else:
            messages.add_message(request, messages.ERROR, "Fail")
    else:
        my_form = forms.MyForm()

    return render_to_response('my_templatle.html', locals(), context_instance=RequestContext(request))
...

my_template.html:
...

{% if messages %}
<ul class="messages">
    {% for message in messages %}
    <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
    {% endfor %}
</ul>
{% endif %}
...

Comments