Last Updated: June 16, 2016
· celc

Bootstrap and Django messages play well together.

One of the pleasant and convenient things with using bootstrap and Django together is that the bootstrap alerts follow the same system as Django (with one exception as of bootstrap 3) http://twitter.github.io/bootstrap/components.html#alerts for instance:

def foo(request):
    messages.success(request, "Huge success!")
    return render(request, 'index.html')

Then in index.html:

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

You'll have a stylish and appropriate message pop up for the user. For Bootstrap 3 you'll need to override the ERROR setting to change error into danger.

    messages.ERROR: 'danger'

5 Responses
Add your response


Good spot! Sadly this doesn't quite work in Bootstrap 3 since the .alert-error class is now .alert-danger.

Edit: scratch that, you can customise the tags (credit to Eric Saupe http://ericsaupe.com/tag/bootstrap-messages-fix/):

MESSAGETAGS = {messageconstants.DEBUG: 'debug',
messageconstants.INFO: 'info',
constants.SUCCESS: 'success',
messageconstants.WARNING: 'warning',
constants.ERROR: 'danger',}

over 1 year ago ·

Oh that's an excellent comment on bootstrap 3. It seems like you only have to override ERROR as the setting extends rather than replaces the default.

over 1 year ago ·
from django.contrib.messages import constants as messages
over 1 year ago ·

Since Django 1.7, this can break if you use "extra_tags", for example in the case described here : http://stackoverflow.com/questions/2053258/how-do-i-output-html-in-a-message-in-the-new-django-messages-framework

If you add an extra_tag called "safe", then the "message.tags" can return "safe error", for example. This would give your message class="alert-safe error".

A solution is to not use {{ message.tags }}, but instead {{ message.level_tag }}.

over 1 year ago ·

Thank you!

over 1 year ago ·