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

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
即可看到数据

你可能感兴趣的:(python学习笔记)