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:

views.py:
======

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
else:
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:

views.py:
=======

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


showall.html:
=========

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


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






Comments