Django messages being displayed twice
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开发者_JAVA百科 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?
Turns out this was a template inheritance issue. Double check and make sure you don't have the same block in two different templates.
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.
精彩评论