8.1 搜索&分页浏览商品信息(附加)

  • 本节案例是建立在第八节《商品信息管理》之上继续开发的,具体效果如下:

(1). 编辑项目urls路由信息配置

  • 打开根路由文件:myobject/myadmin/urls.py路由文件,编辑路由配置信息:
  • 为商品信息浏览路由添加页码参数:url(r'^goods/(?P<pIndex>[0-9]+)$', ... ... ),,具体如下:

from django.conf.urls import url

from myadmin.views import index,users,type,goods

urlpatterns = [
    ...
    # 后台商品信息管理
    url(r'^goods/(?P<pIndex>[0-9]+)$', goods.index, name="myadmin_goods_index"),
    url(r'^goods/add$', goods.add, name="myadmin_goods_add"),
    url(r'^goods/insert$', goods.insert, name="myadmin_goods_insert"),
    url(r'^goods/del/(?P<gid>[0-9]+)$', goods.delete, name="myadmin_goods_del"),
    url(r'^goods/edit/(?P<gid>[0-9]+)$', goods.edit, name="myadmin_goods_edit"),
    url(r'^goods/update/(?P<gid>[0-9]+)$', goods.update, name="myadmin_goods_update"),
]

 (2). 编辑视图文件

  • 新建视图文件:myobject/myadmin/views/goods.py 视图文件,并进行编辑index方法中代码
  • 导入查询Q和分页Paginator:
from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import redirect
from django.core.urlresolvers import reverse
from django.db.models import Q
from django.core.paginator import Paginator

from common.models import Types,Goods
from PIL import Image
from datetime import datetime
import time,json,os

# ==============后台商品信息管理======================
# 浏览商品信息
def index(request,pIndex):
    '''浏览信息'''
    #获取商品类别信息
    tlist = Types.objects.extra(select={'_has':'concat(path,id)'}).order_by('_has')
    for ob in tlist:
        ob.pname = '. . .'*(ob.path.count(',')-1)

    #获取商品信息查询对象
    mod = Goods.objects
    mywhere=[] #定义一个用于存放搜索条件列表

    # 获取、判断并封装关keyword键搜索
    kw = request.GET.get("keyword",None)
    if kw:
        # 查询商品名中只要含有关键字的都可以
        list = mod.filter(goods__contains=kw)
        mywhere.append("keyword="+kw)
    else:
        list = mod.filter()
    # 获取、判断并封装商品类别typeid搜索条件
    typeid = request.GET.get('typeid','0')
    if typeid != '0':
        tids = Types.objects.filter(Q(id=typeid) | Q(pid=typeid)).values_list('id',flat=True)
        list = list.filter(typeid__in=tids)
        mywhere.append("typeid="+typeid)
    # 获取、判断并封装商品状态state搜索条件
    state = request.GET.get('state','')
    if state != '':
        list = list.filter(state=state)
        mywhere.append("state="+state)

    #执行分页处理
    pIndex = int(pIndex)
    page = Paginator(list,5) #以5条每页创建分页对象
    maxpages = page.num_pages #最大页数
    #判断页数是否越界
    if pIndex > maxpages:
        pIndex = maxpages
    if pIndex < 1:
        pIndex = 1
    list2 = page.page(pIndex) #当前页数据
    plist = page.page_range   #页码数列表

    #遍历商品信息,并获取对应的商品类别名称,以typename名封装
    for vo in list2:
        ty = Types.objects.get(id=vo.typeid)
        vo.typename = ty.name
    #封装信息加载模板输出
    context = {'typelist':tlist,"goodslist":list2,'plist':plist,'pIndex':pIndex,'maxpages':maxpages,'mywhere':mywhere,'typeid':int(typeid)}
    return render(request,"myadmin/goods/index.html",context)

# 商品信息添加表单
....
....

(3). 编写模板文件

  • 3.1. 打开父类模板:/templates/myadmin/base.html ,编辑导航栏代码
  • 将为路由myadmin_goods_index添加一个默认页号参数1:
    ...
    <li class="nav-header">
        商品信息管理
    </li>
    <li>
        <a href="{% url 'myadmin_goods_index' 1 %}"><i class="icon-list-alt"></i> 浏览商品信息</a>
    </li>
    <li>
        <a href="{% url 'myadmin_goods_add' %}"><i class="icon-list-alt"></i> 添加商品信息</a>
    </li>
    ...
  • 3.2. 后台商品信息浏览页模板:/templates/myadmin/goods/index.html

  • 在里面添加搜索表单页码信息, 注意: { { mywhere|join:'&' } }是为了下一页维持搜索条件用的:

{% extends "myadmin/base.html" %}

{% block mainbody %}                
<h2>
    商品信息浏览
</h2>
<form class="form-inline" action="{% url 'myadmin_goods_index' 1 %}" method="get">
  <label>关键字:</label>
  <input type="text" name="keyword" value="{{request.GET.keyword}}" class="input-small" placeholder="商品名称">
  <label> &nbsp; 类别:</label>
  <select name="typeid" class="span2">
    <option value="0">全部</option>
    {% for vo in typelist %}
        <option value="{{ vo.id }}" {% if typeid == vo.id %}selected{% endif %}>{{vo.pname}}|--{{ vo.name }}</option>
    {% endfor %}
  </select>
  <label> &nbsp; 状态:</label>
  <select name="state" class="span1">
      <option value="">全部</option>
      <option value="1" {% if request.GET.state == '1' %}selected{% endif %}>新商品</option>
      <option value="2" {% if request.GET.state == '2' %}selected{% endif %}>在售</option>
      <option value="3" {% if request.GET.state == '3' %}selected{% endif %}>已下架</option>
  </select>
  <button type="submit" class="btn">搜索</button>
  <a href="{% url 'myadmin_goods_index' 1 %}" class="btn">全部</a>
</form>
<table class="table table-bordered table-striped">
    <thead>
        <tr>
            <th>id号</th>
            <th>商品名称</th>
            <th>商品类别</th>
            <th>图片</th>
            <th>价格</th>
            <th>点击量</th>
            <th>状态</th>
            <th>操作</th>
        </tr>
    </thead>
    <tbody>
        {% for vo in goodslist %}
        <tr>
            <td>{{ vo.id }}</td>
            <td>{{ vo.goods }}</td>
            <td>{{ vo.typename }}</td>
            <td><img src="/static/goods/s_{{ vo.picname }}" width="40"/></td>
            <td>{{ vo.price }}</td>
            <td>{{ vo.clicknum }}</td>
            <td>
                {% if vo.state == 1 %}
                    <span style="color:green">新商品</span>
                {% elif vo.state == 2 %}
                    在售
                {% elif vo.state == 3 %}
                    已下架
                {% else %}
                    <span style="color:red">无效状态</span>
                {% endif %}
            </td>
            <td>
                <a href="{% url 'myadmin_goods_edit' vo.id %}" class="btn btn-mini btn-primary">编辑</a>
                <a href="{% url 'myadmin_goods_del' vo.id %}" class="btn btn-mini btn-danger">删除</a>
            </td>
        </tr>
        {% endfor %}
    </tbody>
</table>                
<div class="pagination">
    <ul>
        <li>
            <a href="{% url 'myadmin_goods_index' pIndex|add:-1 %}?{{ mywhere|join:'&' }}">&laquo;</a>
        </li>
        {% for p in plist %}
        <li {% if pIndex == p %}class="active"{% endif %}>
            <a href="{% url 'myadmin_goods_index' p %}?{{ mywhere|join:'&' }}">{{p}}</a>
        </li>
        {% endfor %}
        <li>
            <a href="{% url 'myadmin_goods_index' pIndex|add:1 %}?{{ mywhere|join:'&' }}">&raquo;</a>
        </li>

    </ul>
</div>
{% endblock %}

(4). 运行测试