3

I'm using Django's message framework, and I have a very odd problem where my messages are being displayed twice in the template, even though {{messages|length}} is 1

My view

if request.method == 'POST':
    form = EditProfileForm(user=request.user, meta=meta, data=request.POST, files=request.FILES)
    if form.is_valid():
        user = form.save()
        if 'uploaded_image' in request.FILES:
            #TODO limit image size, check mime type
            filename = request.FILES['uploaded_image']
            destination = open('%s/%s' % (settings.FILE_UPLOAD_PATH, form.filename), 'wb+')
            for chunk in filename.chunks():
                destination.write(chunk)
            destination.close() 

        print 'adding success message' #this is printed once
        messages.success(request, 'Settings saved.') #this message is displayed twice
        #messages.add_message(request, messages.SUCCESS, 'Yup. Saved.')

        return HttpResponseRedirect(reverse('someview'))
    else:
        print form.errors
        messages.error(request, 'Error updating settings. See errors below.')

in my template:

{% block message%}
{{message.count}}
{% if messages %}
{{messages|length}}
    {% for message in messages%}
        <p class="{{message.tags}}">{{message}}</p>
    {% endfor %}
{% endif %}
{% endblock %}

Any ideas?

CoolGravatar
  • 5,408
  • 7
  • 35
  • 42

2 Answers2

4

Turns out this was a template inheritance issue. Double check and make sure you don't have the same block in two different templates.

CoolGravatar
  • 5,408
  • 7
  • 35
  • 42
2

While this answer is for a different question, I was having this issue and it helped me resolve it.

To summarize, the following code can be added to settings.py:

MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage'

This changes the messages from being stored in CookiesStorage to SessionStorage, which in some cases are more reliable and prevent double displaying of messages, or not displaying at all.

Unsolved Cypher
  • 1,025
  • 10
  • 24