学习完合集的一到七,现在可以做个练手项目了。
展示用户列表
models.py:
from django.db import models
class UserInfo(models.Model):
name = models.CharField(max_length=32)
password = models.CharField(max_length=64)
age = models.IntegerField()
stu_id = models.IntegerField()
tea_id = models.IntegerField(default=5)
UserInfo.objects.create(name="小傻", password="123", age=11, stu_id=1, tea_id=2)
UserInfo.objects.create(name="小郑", password="456", age=13, stu_id=2, tea_id=3)
views.py
settings.py
确保setting.py上面有注册app01后,添加DATABASES相关的如下代码
DATABASES = {
"default": {
"ENGINE": "django.db.backends.mysql", # 说明我们想要底层去连接mysql
"NAME": 'gx_day15', # 刚创建的学习样例数据库名字
'USER': 'root', # sql用户名
'PASSWORD': '123456', # sql密码
'HOST': 'localhost', # sql连接的主机,默认是本地。127.0.0.1也可以
'PORT': 3307, # 一般为3306
}
}
urls.py
user.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<table border="1">
<thead>
<tr>
<th>ID</th>
<th>姓名</th>
<th>密码</th>
<th>年龄</th>
<th>stu_id</th>
<th>tea_id</th>
</tr>
</thead>
{% for obj in data_list %}
<tbody>
<tr>
<td>{{ obj.id }}</td>
<td>{{ obj.name }}</td>
<td>{{ obj.password }}</td>
<td>{{ obj.age }}</td>
<td>{{ obj.stu_id }}</td>
<td>{{ obj.tea_id }}</td>
</tr>
</tbody>
{% endfor %}
</table>
</body>
</html>
最终效果:
添加用户
注意这时一定要把models.py里的UserInfo.objects.create的两行代码注释掉!因为我们添加用户现在可以从前端拿到数据了,刚刚加上只是因为要展示用户列表,而数据库还没有数据。
views.py
from django.shortcuts import render, HttpResponse, redirect
from app01.models import UserInfo
def showUsers(request):
data_list = UserInfo.objects.all()
return render(request, "user.html", {"data_list": data_list})
def addUser(request):
if request.method == "GET":
return render(request, 'add.html')
user = request.POST.get("user")
pwd = request.POST.get("pwd")
age = request.POST.get("age")
stu_id = request.POST.get("stu_id")
tea_id = request.POST.get("tea_id")
UserInfo.objects.create(name=user, password=pwd, age=age, stu_id=stu_id, tea_id=tea_id)
return redirect("/user") # 跳转回显示用户列表页面
# 相当于 return redirect("http://127.0.0.1:8000/user")
urls.py
add.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form method="post">
{# <form method="post" action="/add/"> 也可以,省略action相当于告诉服务器,我就以当前的网址提交请求。 #}
{% csrf_token %}
<input type="text" name="user" placeholder="姓名">
<input type="text" name="pwd" placeholder="密码">
<input type="text" name="age" placeholder="年龄">
<input type="text" name="stu_id" placeholder="学生序号">
<input type="text" name="tea_id" placeholder="老师序号">
<input type="submit" value="提交">
</form>
</body>
</html>
最终效果
点击提交后
注意:这里的新增的数据的ID不用管,因为中间本人操作了一些次数,用来测试。每次orm都会自增id,所以不是3,而是13。
删除用户
views.py
urls.py
user.html
最终效果
输入路径为127.0.0.1:8000/delete/,会自动跳转到uesr
点击小纯的删除后,页面变为