Monday, May 27, 2013

Messages notification in Django

Firstly, read the documentation carefully:
Following instructions in the documentation to enable messages framework and use it in your django application.


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():
            messages.add_message(request, messages.INFO, "Success")
            messages.add_message(request, messages.ERROR, "Fail")
        my_form = forms.MyForm()

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


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