Django messages not showing after HttpResponseRedirect

后端 未结 2 1813
小蘑菇
小蘑菇 2020-12-31 16:46

Tried tonnes of stuff out there but none of them really helped.

I have a URL for example:

http://localhost:8000/user/edit-transaction/?object_id

相关标签:
2条回答
  • 2020-12-31 17:31

    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.

    0 讨论(0)
  • 2020-12-31 17:44

    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.

    0 讨论(0)
提交回复
热议问题