您的位置:首页 > 数据库

web 框架 Django 学习记录 (二)把数据库中表内容展示在页面

2017-07-03 19:13 701 查看
1.创建项目、应用

django-admin startproject yu1
cd yu1
python manage.py startapp yuApp


2.修改配置

修改yu1\yu1\settings.py文件

INSTALLED_APPS ,添加一行 ‘yuApp’,

TEMPLATES ,修改’DIRS’: [BASE_DIR+”/templates”,],

3.修改 yu1\yu1\urls.py 文件

from yuApp import views
urlpatterns 添加一行    url(r'^order$',views.order),


4.修改yu1\yuApp\views.py

from django.shortcuts import render
import MySQLdb
def get_data(sql):#获取数据库的数据
conn = MySQLdb.connect(conf.test_dbhost,conf.test_user,conf.test_passd,conf.test_dbname,port=8306,charset="utf8")
cur = conn.cursor()
cur.execute(sql)
results = cur.fetchall() # 搜取所有结果
cur.close()
conn.close()
return results
def order(request):# 向页面输出订单
sql = "SELECT order_sn,shop_sn,accept_name,address,org_price,allprice,voucher " \
"FROM `tb_order` ORDER BY order_id DESC LIMIT 50"
m_data = get_data(sql)
return render(request,'order_list.html',{'order':m_data})


5.新建文件\yu1\templates\order_list.html

写入内容

<html>
<head>
<title>订单查询</title>
</head>
<body>
<B>订单展示</B>
<br>
<table border="1">
<tr>
<th>序号</th>
<th>订单编号</th>
<th>门店编号</th>
<th>收货人</th>
<th>详细地址</th>
<th>订单总价</th>
<th>实付金额</th>
<th>入机状态</th>
</tr>

{% for i in order %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ i.0 }}</td>
<td>{{ i.1 }}</td>
<td>{{ i.2 }}</td>
<td>{{ i.3 }}</td>
<td>{{ i.4 }}</td>
<td>{{ i.5 }}</td>
<td>{{ i.6 }}</td>
</tr>
{% endfor %}

</table>
</body>
</html>


6.启动服务

python manage.py runserver 0.0.0.0:8000

7.浏览器输入 127.0.0.1:8000/order

即可看到数据
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐