Django messages not showing after HttpResponseRedirect

ⅰ亾dé卋堺 提交于 2019-11-30 07:30:12

Finally figured it out. Added below in local_settings.py and its working.

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


What was happening ?

The messages were actually getting stored in Cookies (CookieStorage) which is the default Django behaviour. From Django docs:

FallbackStorage is the default storage class. If it isn’t suitable to your needs, you can select another storage class by setting MESSAGE_STORAGE to its full import path, for example:

MESSAGE_STORAGE = 'django.contrib.messages.storage.cookie.CookieStorage'

And what is FallbackStorage ?

This class first uses CookieStorage, and falls back to using SessionStorage for the messages that could not fit in a single cookie. It also requires Django’s contrib.sessions application.

This behavior avoids writing to the session whenever possible. It should provide the best performance in the general case.

And what was happening in my case ?

Messages were getting stored in CookiesStorage, but for some weird reason (I don't know what) but the Messages in CookiesStorage were getting expired or deleted for the 2nd request (i.e. redirection after POST) which should not be happening (because this is not how flashdata works). And after I switched the default MESSAGE_STORAGE to SessionStorage, it started working.

In my case modifying the MESSAGE_STORAGE value as mentioned by @ParagTyagi was not enough. I was having custom change_list.html templates for some admin classes and in those I had to add the following code:

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

Notice that I've commented the <li> tag, otherwise the messages are duplicated.

In addition, there has to be more than one message in the messages object. Otherwise, the messages are not displayed neither. If you have just one message to display (e.g. a confirmation of a success operation), then just add another empty message like:

messages.add_message(self.request, messages.WARNING, "")

After the modifications, remember to restart your web server (e.g. Apache) and clear your browser cache.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!