目标:
用户可以通过网页,向数据库中插入数据
同时,插入后可以跳转到列表页 /students,可以看到最新的结果
完成添加学生功能的基本准备
主要目标,弄一个add_student的页面
-
在学生列表页,添加一个链接。用于点击后可以跳转到新的url
-
弄一个路由对应关系
- 编写视图函数,目前只要让页面可以通就好
- 访问页面,测试是否已经调通
- 弄一个添加学生的表单
表单的设计需要参看一下数据表
mysql> desc student;
+------------+-------------------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+-------------------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(20) | NO | | NULL | |
| gender | enum('男','女','中性','保密') | YES | | 保密 | |
| teacher_id | int(11) | YES | | NULL | |
+------------+-------------------------------+------+-----+---------+----------------+
4 rows in set (0.01 sec)
由此可见,表单中必有的数值要有 name
id由于自增长,不给他也可以的
模板页的代码如下:
<!DOCTYPE html>
<!--作者:pyhui-->
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>添加学生</title>
</head>
<body>
<h1>添加学生</h1>
<form action="" method="post">
<label for="">学生姓名:</label><input type="text"> <br>
<label for="">性别:</label>
<select name="gender" id="">
<option value="男">男</option>
<option value="女">女</option>
<option value="中性">中性</option>
<option selected value="保密">保密</option>
</select>
<br>
<input type="submit">
</form>
</body>
</html>
这里有个小问题。。。
视图函数小做修改
def add_student(request):
method = request.method
print('请求方式', method)
return render(request, "add_student.html")
访问网址时
后端的输出
浏览器发数据给后端
接收不到学生姓名的数据
当提交表单后,后端输出的结果为:
请求方式 POST
<QueryDict: {‘gender’: [‘保密’]}>
寻找原因。类型为text的input框,没有加name属性
注,如果进行表单的提交,相关的表单控件(表单控件指的就是input标签) 如果需要把数据传到服务端,控件的标签应该要有name属性
补上,再传递参数试一试
效果比对
获取POST参数,保存到数据库中
接下来,要把数据保存到mysql中
由于数据库的连接,游标对象的定义等操作代码多且使用频繁
可以考虑把他们封装为一个模块中。需要的时候直接导入。
因此,代码写到这里,先暂停一阵。
完成pymysql的封装再继续。
关于POST请求
明确,如何发起一个POST请求
明确,POST请求的数据是通过什么方式来传输的
POST请求 VS GET请求
GET请求,参数在哪里?
参数在URL地址上
POST请求,参数在哪里?
封装pymysql常用方法
新建一个模块,处理pymysql的操作, 例如: sql_handle.py
代码如下:
# 作者:pyhui
"""数据库功能封装"""
import pymysql
class SqlDb:
def __init__(self):
# 数据库连接对象创建
self.conn = pymysql.connect(
host="127.0.0.1",
port=3306,
user="root",
passwd="root",
db="python2019",
charset="utf8"
)
# 游标对象的创建
self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)
def select_from_table(self, sql, args):
"""
从表中查询所有的数据
:param table_name: 表名称
:return: 全部数据,列表包字典
"""
send_sql = sql.format(*args)
print(send_sql)
self.cursor.execute(send_sql)
return self.cursor.fetchall()
def act_table(self, sql, args):
send_sql = sql.format(*args)
print(send_sql)
self.cursor.execute(send_sql)
self.conn.commit()
print('提交成功')
db = SqlDb
if __name__ == '__main__':
db = SqlDb()
sql = "insert into {} values {}"
args = ("student", (0,"布尔玛","女",2))
db.act_table(sql, args)
继续后端POST参数的写入
代码:
def add_student(request):
method = request.method
print('请求方式', method)
if request.method == "POST":
# 当请求是post请求的时候
get_data = request.POST
name = get_data["name"]
gender = get_data["gender"]
# 把数据存入到mysql中
sql = "insert into student values {}"
args = ((0, name, gender, 2),)
db.act_table(sql, args)
print("数据插入成功", name)
return render(request, "add_student.html")
试着录入数据
后端结果
数据库的内容
mysql> select * from student;
+----+---------+--------+------------+
| id | name | gender | teacher_id |
+----+---------+--------+------------+
| 1 | 子粘 | 男 | 1 |
| 2 | 盆凯 | 男 | 1 |
| 5 | 呈祥 | 男 | 1 |
| 6 | 牛劲 | 男 | 1 |
| 7 | 朋小王 | 男 | 1 |
| 10 | 哪扎 | 保密 | NULL |
| 11 | 布尔玛 | 女 | 2 |
| 12 | 王小虎 | 男 | 2 |
| 13 | 布尔玛2 | 女 | 2 |
| 14 | 李逍遥 | 男 | 2 |
+----+---------+--------+------------+
10 rows in set (0.00 sec)
插入成功
但是问题,插入成功后,没有跳转
期望插入数据成功后,页面跳转到列表页
让我们可看到效果
可考虑使用 redirect来跳转
最终版本代码
后端
def add_student(request):
""" 添加学生 """
method = request.method
print('请求方式', method)
# 当请求类型是GET时
if request.method == "GET":
return render(request, "add_student.html")
# 当请求类型为POST时
if request.method == "POST":
# 当请求是post请求的时候
get_data = request.POST
name = get_data["name"]
gender = get_data["gender"]
# 把数据存入到mysql中
sql = "insert into student values {}"
args = ((0, name, gender, 2),)
db.act_table(sql, args)
print("数据插入成功", name)
return redirect("/students/")
效果