django小案例(一):用户列表展示页面的制作(python+html+mysql综合使用)

在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项目,得到的结果是这个样子~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值