Friday, October 4, 2013

Django - To display message from Message Framework correctly

To be able to display the messages from Django's Message Framework, you have to provide the request context in the return. For example:

def export(request):
csv_file = get_csv_file(request)
if type(csv_file).__name__=='file':
response = HttpResponse(csv_file, mimetype='application/csv')
response['Content-Disposition'] = 'attachment; filename=mycsv.csv'
return response
if excel_file==0:
messages.add_message(request, messages.WARNING, 'No thing.')
return redirect('myapp.views.showall')

If the csv_file is not a file, a message will be added to the message framework, and the user will be redirected back to the showall view. In the showall view, we have to return the request context:

def showall(request):
     return render_to_response('showall.html', locals(), context_instance=RequestContext(request))


{% if messages %}
<ul class="messages" style="color:red">
    {% for message in messages %}
   {% if 'warning' in message.tags %}
    <li>{{ message }}</li>
   {% endif %}
    {% endfor %}
{% endif %}

If I don't return the request context, when the export view redirect user back to showall view, nothing will be displayed.