wekglq
Last Updated: June 16, 2016
·
22.17K
· 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.

MESSAGE_TAGS = {
    messages.ERROR: 'danger'
}

5 Responses
Add your response

12068

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',
message
constants.SUCCESS: 'success',
messageconstants.WARNING: 'warning',
message
constants.ERROR: 'danger',}

over 1 year ago ·
12518

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 ·
12618
from django.contrib.messages import constants as messages
over 1 year ago ·
22037

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 ·
27786

Thank you!

over 1 year ago ·