Django中提示消息messages的设置
1. 引入messages模块
1 from django.contrib import messages
2. 把messages写入view中
1 @csrf_exempt 2 def search(request): 3 if request.method == 'GET': 4 bookname = request.GET.get('bookname') 5 bookinfo = Book.objects.filter(bookname=bookname) 6 is_staff = request.user.is_staff 7 username = request.user.username 8 gonggao = Gonggao.objects.all().order_by("-c_time") 9 liuyanban_all = liuyan.objects.all().order_by("-c_time") 10 c2 = JieInfo.objects.filter(u_name=username, book_name=bookname) 11 c3 = JieInfo.objects.filter(u_name=username).count() 12 if username == '': 13 messages.error(request, '亲,请您先登录,才能使用该功能。') 14 return redirect('/') 15 else: 16 if bookname == '': 17 messages.error(request, '亲,搜索内容不能为空哦。') 18 return redirect('/') 19 elif c2.exists(): 20 messages.error(request, '对不起,您不能再次借阅该图书了。') 21 return redirect('/') 22 elif c3 == 5: 23 messages.error(request, '对不起,您将超出图书馆借阅图书数量限制。') 24 return redirect('/') 25 else: 26 if bookinfo.exists(): 27 return render(request, "systeam/searched.html", 28 {'bookinfo': bookinfo, 'username': username, 'is_staff': is_staff}) 29 else: 30 messages.error(request, '亲,没有这本书呢。') 31 return redirect('/') 32 else: 33 return render(request, "systeam/searched.html", {'username': username})
3. 把messages渲染到页面中
1 {% if messages %} 2 3 <ul class="messages"> 4 5 {% for message in messages %} 6 7 8 <li{%if message.tags %} class="{{ message.tags }}"{% endif %}> 9 <div class="m_title"> 10 {{ message.tags }} 11 <a href="" id="a_tuichu"> 12 <i class="iconfont icon-fork"></i> 13 </a> 14 </div> 15 <div id="m_box"> 16 {{ message }} 17 </div> 18 <a href="" id="a_sure"> 19 <button id="button_sure"> 20 确认 21 </button> 22 </a> 23 </li> 24 25 {% endfor %} 26 27 </ul> 28 29 {% endif %}