本文介绍了Bootstrap/Django错误消息是否没有红色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Django应用程序中处理消息.不幸的是,除了错误消息不是红色之外,每种消息类型似乎都可以正常工作.

我的代码非常简单.

views.py

from django.contrib import messages

def generate_test(request):
  messages.info(request, 'TEST')
  messages.success(request, 'TEST')
  messages.warning(request, 'TEST')
  messages.error(request, 'TEST')
  return render(request, 'test.html')

test.html

{% extends "base_generic3.html" %}
{% load static %}
{% block content %}
{% endblock %}

我的base_generic3.html包含许多其他内容,例如jquery和bootstrap-4集成.但是以下部分用于以bootstrap-4样式显示消息:

...
{% if messages %}
{% for message in messages %}
<div class="alert alert-{{ message.tags }} alert-dismissible text-center" role="alert">
     <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span>
     </button>
     <strong>{% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}Error{% else %}{{ message.tags|title }}{% endif %}!
     </strong> {{ message }}
 </div>
 {% endfor %}
 {% endif %}
 ...
解决方案

问题是Django的默认消息标签与Bootstrap的上下文类不完全匹配. Bootstrap使用上下文类danger表示红色.您可以将 MESSAGE_TAGS 设置添加到您的settings.pydanger标记应用于级别为messages.ERROR的邮件.

settings.py

from django.contrib.messages import constants as messages
MESSAGE_TAGS = {
    messages.ERROR: 'danger',
}

I wanted to play around with messages in my Django-application. Unfortunately every messagetype seems to work as expected except the error message is not red.

My Code is very simple.

views.py

from django.contrib import messages

def generate_test(request):
  messages.info(request, 'TEST')
  messages.success(request, 'TEST')
  messages.warning(request, 'TEST')
  messages.error(request, 'TEST')
  return render(request, 'test.html')

test.html

{% extends "base_generic3.html" %}
{% load static %}
{% block content %}
{% endblock %}

My base_generic3.html contains a lot of other content like jquery and bootstrap-4 integrations. But the below part is for displaying the message in bootstrap-4 style:

...
{% if messages %}
{% for message in messages %}
<div class="alert alert-{{ message.tags }} alert-dismissible text-center" role="alert">
     <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span>
     </button>
     <strong>{% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}Error{% else %}{{ message.tags|title }}{% endif %}!
     </strong> {{ message }}
 </div>
 {% endfor %}
 {% endif %}
 ...
解决方案

The issue is that Django's default message tags do not match perfectly with Bootstrap's contextual classes. Bootstrap uses the contextual class danger for the color red. You can add the MESSAGE_TAGS setting to your settings.py to apply the danger tag to messages with the level messages.ERROR.

settings.py

from django.contrib.messages import constants as messages
MESSAGE_TAGS = {
    messages.ERROR: 'danger',
}

这篇关于Bootstrap/Django错误消息是否没有红色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 23:55