1.展示用户列表
url
函数:
获取所有用户信息
HTML渲染
return render(request,"info_list.html",{"data_list":data_list})
{% for obj in data_list %}
<tr>
<td>{{ obj.id }}</td>
<td>{{ obj.name }}</td>
<td>{{ obj.password }}</td>
<td>{{ obj.age }}</td>
</tr>
{% endfor %}
2.添加用户
url
函数:
GET,看到页面,输入内容。
POST,提交->写入到数据库。
path('info/list/',views.info_list),
path('info/add/',views.info_add),
def info_add(request):
if request.method == 'GET':
return render(request, 'info_add.html')
# 获取用户提交数据
user = request.POST.get("user")
pwd = request.POST.get("pwd")
age = request.POST.get("age")
# 添加到数据库
UserInfo.objects.create(name=user,password=pwd,age=age)
# return HttpResponse("添加成功")
# 自动跳转
return redirect("/info/list/")
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>添加用户</h1>
<form method="post" action="/info/add/">
{% csrf_token %}
<input type="text" name="user" placeholder="用户名">
<input type="text" name="pwd" placeholder="密码">
<input type="text" name="age" placeholder="年龄">
<input type="submit" value="提交">
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>INFO列表</h1>
<a href="/inof/add/">添加</a>
<table border="1">
<thead>
<tr>
<th>ID</th>
<th>姓名</th>
<th>密码</th>
<th>年龄</th>
</tr>
</thead>
<tbody>
{% for obj in data_list %}
<tr>
<td>{{ obj.id }}</td>
<td>{{ obj.name }}</td>
<td>{{ obj.password }}</td>
<td>{{ obj.age }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
3.删除用户
url
函数:
def info_delete(request):
nid = request.GET.get('nid')
UserInfo.objects.filter(id=nid).delete()
return redirect("/info/list/")
在对应的主页面html上做如下改动
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>INFO列表</h1>
<a href="/info/add/">添加</a>
<table border="1">
<thead>
<tr>
<th>ID</th>
<th>姓名</th>
<th>密码</th>
<th>年龄</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for obj in data_list %}
<tr>
<td>{{ obj.id }}</td>
<td>{{ obj.name }}</td>
<td>{{ obj.password }}</td>
<td>{{ obj.age }}</td>
<td>
<a href="/info/delete/?nid={{ obj.id }}">删除</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>