(转)Django ====> 实战学习篇八 增加目录页,设置统一布局
对于这个项目,我们增加一个目录页,用来显示物品,并且提供加入购物车的按钮,对于模板,我们进行统一设置,根据继承模板的操作对子模板进行重写,弄好整体的风格设定,并完成设计。类似如下风格:
前面的scaffold内容说明了模板的内容,我们把统一的内容写到base.html中,先不做这个,先来实现目录页。我的顺序是:
- 修改URLconf 叫做/depotapp/store,在url中加入下边这行:
/depotapp/urls.py (r'^store', store_view),
- 修改视图函数view,store是其对应的视图函数,在depotapp的views里加入下边的内容:
/depotapp/views.py import datetime def store_view(request): products = Product.objects.filter(date_available__gt=datetime.datetime.now().date()) .o rder_by("-date_available") #products = Product.objects.all() 上边的不行用这行先代替 t = get_template('depotapp/store.html') c = RequestContext(request,locals()) return HttpResponse(t.render(c))
- 使用/depot/templates/depotapp/store.html作为模板,代码如下:
{% extends "base.html" %} {% block title %} 产品目录 {% endblock %} {% block pagename %} 产品目录 {% endblock %} {% block content %} {% for item in products %} <div class="row" style="padding-top:10"> <div class="span3 media-grid"> <a href="#"> <img class="thumbnail" src="{{item.image_url}}" alt=""> </a> </div> <div class="span-two-thirds"> <h3>{{item.title}}</h3> <br/> {{item.description}} <br/> <br/> <br/> <div class="row"> <div class="span2"><h3>¥{{item.price|floatformat:"2"}}</h3></div> <div class="span"><a class="btn primary" href="#">加入购物车</a></div> </div> </div> </div> <div class="page-header"> </div> {% endfor %} {% endblock %}
- 上边的模板继承了base.html,修改base.html ,并加入共用的内容部分,为整个站点设计了风格布局,代码如下:
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="description" content="a depot implement with Django"/> <meta name="keywords" content="django,depot" /> <meta name="author" content="Holbrook(http://hi.csdn.net/space-2668.html)" /> <title>{% block title %} 标题 {% endblock %}</title> <!-- Le HTML5 shim, for IE6-8 support of HTML elements --> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <!-- Le styles --> <link rel="stylesheet" href="/static/css/bootstrap.min.css"> <link rel="stylesheet" href="/static/css/layout.css"> </head> <body> <div class="topbar"> <div class="fill"> <div class="container"> <a class="brand" href="#">Depot</a> <ul class="nav"> <li class="active"><a href="#">首页</a></li> <li><a href="#about">问题</a></li> <li><a href="#contact">新闻</a></li> <li><a href="#contact">联系我们</a></li> </ul> <form action="" class="pull-right"> <input class="input-small" type="text" placeholder="用户名"> <input class="input-small" type="password" placeholder="密码"> <button class="btn" type="submit">登录</button> </form> </div> </div> </div> <div class="container"> <div class="content"> <div class="page-header"> <h1>{% block pagename %} 页面名称 {% endblock %}</h1> </div> {% block content %} 内容 {% endblock %} </div><!-- /content --> </div><!-- /container --> </body> </html>
用了很少的代码增加了目录页,并且设计了网页的整体布局。
“某度”空间 http://hi.baidu.com/new/wenjiashe521
cnblogs空间 http://www.cnblogs.com/wenjiashe521/