How to pass a message from HttpResponseRedirect in Django?

from django.contrib import messages
messages.success(request, _('Thank you'))
return redirect('/whatever/')

Adding a more elaborative answer.

1: Configure a message storage in your settings.py:

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

or if you are not using sessions, use CookieStorage:

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

2: In your view, import django.contrib.messages:

from django.contrib import messages

3: Set the message data before returning the HttpResonse:

messages.success(request, 'Changes successfully saved.')

which is a shorthand for:

messages.add_message(request, messages.SUCCESS, 'Changes successfully saved.')

The message tags (messages.SUCCESS in this case) can then be used in your template to i.e. add a corresponding CSS-class or hide debug-messages. Django includes a few by default but if you wish to use this with Bootstrap's default alert classes you will need to add some custom message tags for the missing ones.

4: In your template you can then use the messages like this if you are using Bootstrap alerts:

{% if messages %}
    {% for message in messages %}
        <div class="alert {% if message.tags %}alert-{{ message.tags }}{% endif %}" role="alert">{{ message }}</div>
    {% endfor %}
{% endif %}

For example, Django uses 'error' as the default tag for ERROR while Bootstrap uses danger to indicate errors. The best solution is to use custom tags, but you can also monkeypatch it in your template (ugly solution):

{% if messages %}
    {% for message in messages %}
            <div class="alert {% if message.tags %}alert-{% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}danger{% else %}{{ message.tags }}{% endif %}{% endif %}" role="alert">{{ message }}</div>
    {% endfor %}
{% endif %}

Be careful when using i18n urls! If you use a link like /whatever/ but use internationalization, it will redirect to /en/whatever/, thus losing the message in the request. If you use internationalization, always pass the language to the URL:

from django.contrib import messages
from django.utils.translation import get_language

messages.success(request, _('Thank you'))
return redirect('/%s/whatever/' % get_language())

Cost me a couple hours to understand this...


Use the messages framework to send messages between page requests.

Tags:

Django