Django中提示消息messages的设置方式

yipeiwu_com5年前Python基础

1. 引入messages模块

from django.contrib import messages

2. 把messages写入view中

@csrf_exempt
def search(request):
  if request.method == 'GET':
    bookname = request.GET.get('bookname')
    bookinfo = Book.objects.filter(bookname=bookname)
    is_staff = request.user.is_staff
    username = request.user.username
    gonggao = Gonggao.objects.all().order_by("-c_time")
    liuyanban_all = liuyan.objects.all().order_by("-c_time")
    c2 = JieInfo.objects.filter(u_name=username, book_name=bookname)
    c3 = JieInfo.objects.filter(u_name=username).count()
    if username == '':
      messages.error(request, '亲,请您先登录,才能使用该功能。')
      return redirect('/')
    else:
      if bookname == '':
        messages.error(request, '亲,搜索内容不能为空哦。')
        return redirect('/')
      elif c2.exists():
        messages.error(request, '对不起,您不能再次借阅该图书了。')
        return redirect('/')
      elif c3 == 5:
        messages.error(request, '对不起,您将超出图书馆借阅图书数量限制。')
        return redirect('/')
      else:
        if bookinfo.exists():
          return render(request, "systeam/searched.html",
                 {'bookinfo': bookinfo, 'username': username, 'is_staff': is_staff})
        else:
          messages.error(request, '亲,没有这本书呢。')
          return redirect('/')
  else:
    return render(request, "systeam/searched.html", {'username': username})

3. 把messages渲染到页面中

{% if messages %}

  <ul class="messages">

  {% for message in messages %}


    <li{%if message.tags %} class="{{ message.tags }}"{% endif %}>
      <div class="m_title">
        {{ message.tags }}
        <a href="" id=" rel="external nofollow" rel="external nofollow" a_tuichu">
          <i class="iconfont icon-fork"></i>
        </a>
      </div>
      <div id="m_box">
        {{ message }}
      </div>
      <a href="" id=" rel="external nofollow" rel="external nofollow" a_sure">
        <button id="button_sure">
        确认
        </button>
      </a>
    </li>

  {% endfor %}

  </ul>

  {% endif %}

以上这篇Django中提示消息messages的设置方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

跟老齐学Python之print详解

eval() 在print干事情之前,先看看这个东东。不是没有用,因为说不定某些时候要用到。 复制代码 代码如下: >>> help(eval)  ...

python shutil文件操作工具使用实例分析

这篇文章主要介绍了python shutil文件操作工具使用实例分析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 python中的s...

Python对两个有序列表进行合并和排序的例子

假设有2个有序列表l1、l2,如何效率比较高的将2个list合并并保持有序状态,这里默认排序是正序。 思路是比较简单的,无非是依次比较l1和l2头部第一个元素,将比较小的放在一个新的列表...

Python中logging模块的用法实例

本文实例讲述了logging模块的用法实例,分享给大家供大家参考。具体方法如下: import logging import os log = logging.getLogg...

python使用matplotlib画饼状图

python使用matplotlib画饼状图

本文实例为大家分享了python使用matplotlib画饼状图的具体代码,供大家参考,具体内容如下 代码与详细注释 from matplotlib import pyplot...