You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Django messages新增NOTICE常量并适配Bootstrap样式?

如何在Django的messages框架中新增NOTICE消息类型并结合Bootstrap使用

原生Django的django.contrib.messages.constants中并没有NOTICE内置常量,直接引用会触发AttributeError。以下是完整的解决步骤:

步骤1:定义NOTICE常量并配置MESSAGE_TAGS

在settings.py中手动定义NOTICE的数值(需避开原生常量已使用的数值:DEBUG=10、INFO=20、SUCCESS=25、WARNING=30、ERROR=40),并将其加入MESSAGE_TAGS映射:

# settings.py
from django.contrib.messages import constants as messages

# 定义NOTICE常量,选择未被占用的数值
NOTICE = 22

MESSAGE_TAGS = {
    messages.DEBUG: 'alert-secondary',
    messages.INFO: 'alert-info',
    messages.SUCCESS: 'alert-success',
    messages.WARNING: 'alert-warning',
    messages.ERROR: 'alert-danger',
    NOTICE: 'alert-primary',  # 绑定Bootstrap的alert-primary样式
}

步骤2:发送NOTICE类型消息

方式1:直接使用原生API发送

在视图中通过messages.add_message()调用自定义的NOTICE常量:

# views.py
from django.contrib import messages
from django.conf import settings

def sample_view(request):
    # 发送NOTICE类型消息
    messages.add_message(request, settings.NOTICE, "这是一条系统通知")
    return render(request, 'sample_page.html')

方式2:封装快捷函数(可选)

如果想和原生messages.info()、messages.success()一样便捷调用,可在项目中新建工具模块(如utils/messages.py):

# utils/messages.py
from django.contrib import messages
from django.conf import settings

def notice(request, message, extra_tags='', fail_silently=False):
    messages.add_message(request, settings.NOTICE, message, extra_tags=extra_tags, fail_silently=fail_silently)

在视图中导入使用:

# views.py
from .utils.messages import notice

def sample_view(request):
    notice(request, "这是一条封装后的通知消息")
    return render(request, 'sample_page.html')

步骤3:模板中渲染消息

确保模板能正确渲染所有消息类型,包括新增的NOTICE:

<!-- templates/base.html -->
{% if messages %}
    {% for message in messages %}
        <div class="alert {{ message.tags }} alert-dismissible fade show" role="alert">
            {{ message }}
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    {% endfor %}
{% endif %}

配置完成后,NOTICE类型的消息会自动应用Bootstrap的alert-primary样式,实现蓝色通知效果。

内容的提问来源于stack exchange,提问作者Majoris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 12:44:52