django没有工作警觉

问题描述 投票:-1回答:1

django 2.0.2 mac os 10.13 python 3.6.4

我想使用警报模板

django settings.py

MESSAGE_TAGS = {
messages.DEBUG: 'alert-info',
messages.INFO: 'alert-info',
messages.SUCCESS: 'alert-success',
messages.WARNING: 'alert-warning',
messages.ERROR: 'alert-danger',
}

views.py
def list(request)
    messages.error(request,'invalid user', extra_tags='alert')
    return redirect('/')

templates.html

我试过两种方式

template1.html

 {% if messages %}
  <script>
  {% for message in messages %}
  alert({{message}})
  {% endfor %}
  </script>
  {% endif %}

template2.html

<div class="content container">
  {% if messages %}
  {% for message in messages %}
  <div class="alert {{ message.tags }} alert-dismissible" role="alert">
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
      <span aria-hidden="true">&times;</span>
    </button>
    {{ message }}
  </div>
  {% endfor %}
  {% endif %}
    <div class="row">
        <div class="col-md-8">

template2.html结果如下:

<div class="alert alert alert-danger alert-dismissible" role="alert">
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
          <span aria-hidden="true">×</span>
        </button>
        invalid user
      </div>

这个图像的HTML代码这个HTML有效吗?

我不能在django中使用警报..

javascript django
1个回答
0
投票

模板代码看起来有效。您的问题可能是您的视图功能中没有成功添加任何消息。

消息的使用在文档中进行了解释。 https://docs.djangoproject.com/en/2.0/ref/contrib/messages/#using-messages-in-views-and-templates

messages.ERROR不是函数,它只是常量数字代码50要添加错误消息,请使用函数messages.error()

views.py

from django.contrib import messages

def list(request):
    messages.error(request,'invalid user', extra_tags='alert')
    return redirect('/')

您的list视图应该引起异常。这是无效的语法(在def语句中缺少:)以及数字messages.ERROR不可调用。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.