Django框架学习(案例一)
Django框架学习(案例)
案例一: 用户信息管理
0. 前期配置
url绑定
# urls.py
urlpatterns = [
path("login/", views.login),
path("index/", views.index),
path("orm/", views.orm),
path("user/list/", views.user_list),
path("user/add/", views.user_add),
path("user/delete/", views.user_delete)
, ]
建立数据库
# models.py
class UserInfo(models.Model):
"""用户信息表"""
name = models.CharField(verbose_name="用户名", max_length=32)
password = models.CharField(verbose_name="密码", max_length=64)
age = models.IntegerField(verbose_name="年龄", default=0)
1. 展示用户列表
- url
- 函数
- 获取所有用户信息
- HTML渲染
# views.py
def user_list(request):
# 获取数据库中所有用户信息
data_list = UserInfo.objects.all()
return render(request, "user_list.html", {"data": data_list})
简易的表格罗列
<!-- user_list.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户列表</title>
</head>
<body>
<h1>用户信息列表</h1>
<table border="1">
<thead>
<tr>
<th>ID</th>
<th>姓名</th>
<th>密码</th>
<th>年龄</th>
</tr>
</thead>
<tbody>
{% for obj in data %}
<tr>
<td>{{ obj.id }}</td>
<td>{{ obj.name }}</td>
<td>{{ obj.password }}</td>
<td>{{ obj.age }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
2. 添加用户
- url
- 函数
- GET, 看到页面,输入内容
- POST, 提交->写入数据库
# views.py
def user_add(request):
if request.method == "GET":
return render(request, "uesr_add.html")
else:
# 获取数据
user = request.POST.get("user")
password = request.POST.get("password")
age = request.POST.get("age")
# 添加到数据库
UserInfo.objects.create(name=user, password=password, age=age)
return redirect("/user/list/")
简易的表单填写
<!-- user_add.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>添加用户</title>
</head>
<body>
<h1>添加用户</h1>
<form method="post" action="/user/add/">
{% csrf_token %}
<input type="text" name="user" placeholder="用户名">
<input type="password" name="password" placeholder="密码">
<input type="text" name="age" placeholder="年龄">
<input type="submit" value="提交">
</form>
</body>
</html>
改进:
在user/list/
页面提供添加入口
<!-- user_list.html -->
<h1>用户信息列表</h1>
<a href="/user/add/">添加</a>
<table border="1">
3. 删除用户
- url
- 函数
-
传参: 通过url传参
/user/delete/?nid=1 request.POST.get("nid")
-
# views.py
def user_delete(request):
if request.method == "GET":
id = request.GET.get("nid")
UserInfo.objects.filter(id=id).delete()
return redirect("/user/list/")
传参访问比较麻烦,考虑把删除选项放在user/list/
表格右部:
<!-- user_list.html -->
<!DOCTYPE html>
...
<h1>用户信息列表</h1>
<a href="/user/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 %}
<tr>
<td>{{ obj.id }}</td>
<td>{{ obj.name }}</td>
<td>{{ obj.password }}</td>
<td>{{ obj.age }}</td>
<td>
<a href="/user/delete/?nid={{ obj.id }}">删除</a> <!删除入口>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
效果
user/list/:
user/add/:
user/delete/: