尝试让引导弹出窗口和 django 消息正常工作。问题是我不明白如何正确执行此操作,以便如果上下文中有消息,它将显示在网站的右上角。
文档:https://getbootstrap.com/docs/4.3/components/toasts/
Django v3.1.6 和 Bootstrap v4.5
项目的静态文件中有 bootstrap.bundle.js,它也包含在基础模板中。我不擅长 django 的布局,所以我将非常感谢您提供最详细的答案。
您可以使用
MESSAGE_TAGS
设置修改模板中显示的消息类别。
将此添加到您的
settings.py
MESSAGE_TAGS = {
messages.DEBUG: 'alert-info',
messages.INFO: 'alert-info',
messages.SUCCESS: 'alert-success',
messages.WARNING: 'alert-warning',
messages.ERROR: 'alert-danger',
}
然后将它们显示在您的模板中(最好在您的基本模板中)
{% for message in messages %}
<div class="alert {{ message.tags }} alert-dismissible shadow fade show" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
{{ message | safe }}
</div>
{% endfor %}
你需要
a) 在视图中创建消息
b) 将消息部分添加到模板中
在模板中您需要添加如下内容:
{% if messages %}
<div class="add-your-bootstrap-classes-here-if-needed">
{% for msg in messages %}
<!-- add your message displaying html here -->
{% endfor %}
</div>
{% endif %}
在视图中,您只需使用 Django 消息传递框架文档中列出的方法之一https://docs.djangoproject.com/en/3.1/ref/contrib/messages/.
我用类似的东西:
{% for message in messages %}
<div class="alert {% for tag in message.extra_tags.split %}
{{tag}} {%endfor%} fade show"
role="alert">
<div class="d-flex justify-content-end">
<button type="button"
class="close btn-sm btn btn-danger"
data-dismiss="alert"
aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<hr>
<p class="text-center">
{{ message | safe }}
</p>
</div>
{% endfor %}
{% block main%}
在视图函数中,您应该像这样传递 extra_tags:
messages.success(self.request, "messge here", "alert-success alert-dismissible")
与之前的答案大致相同,但对于 bootstrap5:
(添加settings.py的导入)
# settings.py
from django.contrib import messages
MESSAGE_TAGS = {
messages.DEBUG: 'alert-info',
messages.INFO: 'alert-info',
messages.SUCCESS: 'alert-success',
messages.WARNING: 'alert-warning',
messages.ERROR: 'alert-danger',
}
用 data-bs-dismiss 替换 data-dismiss(bootstrap5 更改)
<!--base.html-->
{% for message in messages %}
<div class="alert {{ message.tags }} alert-dismissible shadow fade show" role="alert">
<button type="button" class="close" data-bs-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
{{ message | safe }}
</div>
{% endfor %}
基于 dan 的回答,更新的引导程序版本(5.3):
将此添加到
settings.py
from django.contrib import messages
MESSAGE_TAGS = {
messages.DEBUG: 'alert-info',
messages.INFO: 'alert-info',
messages.SUCCESS: 'alert-success',
messages.WARNING: 'alert-warning',
messages.ERROR: 'alert-danger',
}
在模板中使用它:
{% for message in messages %}
<div class="alert alert-dismissible {{ message.tags }}" role="alert">
<div>{{ message | safe }}</div>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
{% endfor %}