用户管理页面设计
home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>欢迎进入</title>
</head>
<body>
<center>
<h1>学生信息管理系统</h1>
<h1>这是学生列表</h1>
<a href="/studentapp/add/">添加学生</a>
<a href="/studentapp/find/">查找学生</a>
<table border="1xp ">
<thead>
<tr>
<th>序号</th>
<th>id</th>
<th>用户名</th>
<th>年龄</th>
<th>密码</th>
<th>邮箱</th>
<th>操作1</th>
<th>操作2</th>
</tr>
</thead>
{% for row in student_list %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{row.id}}</td>
<td>{{row.name}}</td>
<td>{{row.age}}</td>
<td>{{row.user_password}}</td>
<td>{{row.email}}</td>
<td><a href="/studentapp/delete/?id={{ row.id }}">删除学生</a></td>
<td><a href="/studentapp/edit/?id = {{row.id}}">修改</a></td>
</tr>
{% endfor %}
</table>
</center>
</body>
</html>
效果如图:
添加学生
理一下添加学生的逻辑(默认该学生是新的):
点击“添加学生”——>跳转到填充该学生信息的页面——>在输入学生信息后点击“提交”,点击“返回”按钮,返回home.html,同时看到刚添加的学生信息。
首先,home页面,点击“添加学生”,根据:
<a href="/studentapp/add/">添加学生</a>,
通过路由:
url(r'^add/$', views.add),调用add函数,
跳转到add_student.html页面,函数如下:
def add(request):
return render(request,"add_student.html")
add_student.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--数据提交给add_student函数-->
<form action="/studentapp/add_student/" method="POST">
<!--防止被攻击-->
{% csrf_token %}
<p>
姓名<input type="text" name = "name">
</p>
<p>
年龄<input type="text" name = "age">
</p>
<p>
email<input type="text" name = "email">
</p>
<p>
密码<input type="text" name = "password">
</p>
<p>
<button type = "submit" class = "btn">添加</button>
</p>
</form>
<p><a href = '/studentapp/home/'>返回</a></p>
</body>
</html>
效果:
app.urls
填充后点击 添加/提交 ,通过路由
url(r'^add_student/$', views.add_student),#传到add_student函数里
add_student函数
def add_student(request):
#解读request
if request.method=="POST":
#获取表单内容
student_name = request.POST.get("name")
student_age = request.POST.get("age")
student_email = request.POST.get("email")
student_password = request.POST.get("password")
#保存到数据库
models.student.objects.create(name = student_name,age = student_age,email = student_email,user_password = student_password)#注意字段名要与自己数据库中的字段名一致,和前面注册和登陆时的要求一样。
#return redirect("/studentapp/student_list")
return HttpResponseRedirect(reverse('add1'))
if request.method == "GET":
obj = models.student.objects.all()
return render(request,"home.html",{'student_list':obj})
#return HttpResponseRedirect(reverse('add1'))用来重定向,防止页面重复提交。需要在路由里加入: url(r'^add1/$', views.add,name = 'add1'),点击添加后,会重定向到添加页面的初始状态,点击返回到达home主页面便可以看到刚添加的学生,
效果:
点击添加后重定向到add1,调用的还是add函数:
点击返回后到达home页面: