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

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容