qliq
qliq

Reputation: 11807

Django 1.6 messages not showing up

I followed the docs to import necessary stuff into my settings, views and template. However, no messaging is showing up.

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    # Uncomment the next line for simple clickjacking protection:
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',

Example view:

from django.contrib import messages

def add_news(request):
    if request.method == 'POST':
        form = NewsForm(request.POST)
        if form.is_valid():
            form.save()
            messages.info(request, "News was added") 
            return HttpResponseRedirect('/')

    if request.method == 'GET':
        form = NewsForm()
        args = {}
        args.update(csrf(request))
        args['form'] = form
        return render_to_response('news/add_news.html', args)

In base.html I have:

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

How should I debug this?

Upvotes: 0

Views: 271

Answers (1)

Timmy O&#39;Mahony
Timmy O&#39;Mahony

Reputation: 53971

The messaging framework makes use of a context_processor to deliver the messages to the template. To make sure the variables from your context_processors are actually added to the context you render your template with, you have to use a RequestContext in your view.

If you’re using the context processor, your template should be rendered with a RequestContext. Otherwise, ensure messages is available to the template context.

You are using the render_to_response method which doesn't do this by default. You either need to specify the use of a RequestContext or use the render function instead which does this by default

return render_to_response('news/add_news.html',
                      args,
                      context_instance=RequestContext(request))

Upvotes: 2

Related Questions