添加更详尽的答案。
1:在您的settings.py中配置消息存储:
MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage'
或者如果您不使用会话,请使用 CookieStorage:
MESSAGE_STORAGE = 'django.contrib.messages.storage.session.CookieStorage'
2:在您看来,导入django.contrib.messages:
from django.contrib import messages
3:设置返回HttpResonse前的消息数据:
messages.success(request, 'Changes successfully saved.')
这是以下的简写:
messages.add_message(request, messages.SUCCESS, 'Changes successfully saved.')
然后可以在模板中使用消息标签(在这种情况下为messages.SUCCESS ),即添加相应的 CSS 类或隐藏调试消息。Django 默认包含一些,但如果您希望将其与 Bootstrap 的默认警报类一起使用,您将需要为缺少的添加一些自定义消息标签。
4:如果您正在使用 Bootstrap 警报,则可以在您的模板中使用如下消息:
{% if messages %}
{% for message in messages %}
<div class="alert {% if message.tags %}alert-{{ message.tags }}{% endif %}" role="alert">{{ message }}</div>
{% endfor %}
{% endif %}
例如,Django 使用 'error' 作为 ERROR 的默认标记,而 Bootstrap 使用危险来指示错误。最好的解决方案是使用自定义标签,但您也可以在模板中对其进行猴子补丁(丑陋的解决方案):
{% 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 %}