Warning: Creating default object from empty value in /membri/bancaldo/wp-content/plugins/paged-comments/paged-comments.php on line 31
bancaldo™ » Django: bootstrap3 template messages
Home > Django > Django: bootstrap3 template messages

Django: bootstrap3 template messages

9 novembre 2016

Per la gestione dei messaggi con django e bootstrap3,
aggiungere al file myapp/templatetags/app_filters.py

# noinspection PyUnresolvedReferences
from django import template


register = template.Library()

@register.assignment_tag
def get_bootstrap_alert_msg_css_name(tags):
    return 'danger' if tags == 'error' else tags

e nella template myapp/templates/base.html dalla quale ereditano tutte le altre:

{% load staticfiles %}
{# Load the tag library #}
{% load bootstrap3 %}
{# Load CSS and JavaScript #}
{% bootstrap_css %}
{% bootstrap_javascript %}
{% load app_filters %}
...
<html>
    <head>
      <title>{% block title %}Myapp{% endblock %}</title>
    </head>
    <body>
      {% if messages %}
        <ul class="list-unstyled messages">
        {% for message in messages %}
          {% get_bootstrap_alert_msg_css_name message.tags as alert_tag %}
          <li class="alert alert-{{ alert_tag }}">{{ message }}</li>
        {% endfor %}
        </ul>
      {% endif %}

      <div class="content container">
        <div class="row">
          <div class="col-md-8">
            {% block content %}
            {% endblock %}
          </div>
        </div>
        <br>
      </div>
    </body>
</html>

All’interno di views.py:

from django.contrib import messages

def a_view(request):
    ...
    messages.warning(request, "warning message")
    messages.info(request, "info message")
    messages.error(request, "error message")
    messages.success(request, "success message")
    ...
Categorie:Django Tag:
I commenti sono chiusi.