2019-01-09 Django把数据库中表内容展示在页面

2019-01-09  本文已影响0人  张大志的博客

1、环境准备

python3环境
pip3 install django

2、创建项目、应用

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

3、修改配置

vim /data/yu1/yu1/settings.py 
ALLOWED_HOSTS = ['*']
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'yuApp'   #将应用添加进来
]
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR+"/templates",],   #设定templates目录的位置
        'APP_DIRS':  True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

4、修改 yu1\yu1\urls.py 文件

vim /data/yu1/yu1/urls.py 
from yuApp import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('order',views.order),  #增加此行内容
]

5、修改yu1\yuApp\views.py

vim /data/yu1/yuApp/views.py
from django.shortcuts import render
import MySQLdb
def get_data(sql):#获取数据库的数据
    conn = MySQLdb.connect('127.0.0.1','root','123456','test',port=3306)   #test为数据库名
    cur = conn.cursor()
    cur.execute(sql)
    results = cur.fetchall() # 搜取所有结果
    cur.close()
    conn.close()
    return results
def order(request):# 向页面输出订单
    sql = "select * from t" #t为表名
    m_data = get_data(sql)
    return render(request,'order_list.html',{'order':m_data})

6、新建文件\yu1\templates\order_list.html

vim /data/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>
        </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>

7、修改init.py文件

因为python3不能使用import MySQLdb,所以要先安装pymysql

pip3 install pymysql
vim /data/yu1/yu1/__init__.py
import pymysql
pymysql.install_as_MySQLdb()

8、启动服务

python3 manage.py runserver 0.0.0.0:8000

9、浏览器访问

 http://ip:8000/order  #就可以看到数据库中的内容

参考:https://blog.csdn.net/zhizunyu2009/article/details/74255543

上一篇 下一篇

猜你喜欢

热点阅读