在urls.py文件下添加一个新的路径:
from django.contrib import admin
from django.urls import path
from app01.views import *
urlpatterns = [
path('admin/', admin.site.urls),
#用户信息展示界面
path('UserList/',userList),
]
然后打开views.py文件,在其中编写与上述相同名称的函数userList:
#这里要先读取数据库中存放的相关数据,需要先引入models.py文件
#app01是我的app文件夹名称
from app01.models import *
def userList(request):
dataList=userInfo.objects.all()
return render(request,"userList.html" ,{"dataList":dataList})
我的models.p文件如下:
from django.db import models
# Create your models here.
class userInfo(models.Model):
name=models.CharField(max_length=32)
password=models.CharField(max_length=16)
age=models.IntegerField()
数据库中已经事先存放了一些数据,这是在命令行中输入命令展示的已有数据:
mysql> select * from app01_userinfo;
+----+--------+----------+-----+
| id | name | password | age |
+----+--------+----------+-----+
| 1 | root | 123456 | 16 |
| 2 | root | 123456 | 16 |
| 3 | root | 123456 | 16 |
| 4 | root | 123456 | 16 |
| 5 | root | 123456 | 16 |
| 6 | 12123 | 112346 | 14 |
| 7 | 121553 | 1897 | 23 |
+----+--------+----------+-----+
7 rows in set (0.00 sec)
下面来设计html页面,名称与views.py中的一致,存放在temblates文件夹中:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>用户列表</h1>
<table>
<thead>
<tr>
<th>id</th>
<th>用户名</th>
<th>密码</th>
<th>年龄</th>
</tr>
</thead>
<tbody>
{% for obj in dataList %}
<tr>
<th>{{obj.id}}</th>
<th>{{obj.name}}</th>
<th>{{obj.password}}</th>
<th>{{obj.age}}</th>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
最后在命令行运行该django项目,得到的结果是这个样子~