一、students.py文件
from django.shortcuts import render,redirect
from app01 import models
def get_students(request):
stu_list = models.Students.objects.all()
# print(cls_list)
return render(request,"get_students.html",{"stu_list":stu_list})
def add_students(request):
if request.method == "GET":
cs_list = models.Classes.objects.all()
return render(request, "add_students.html",{"cs_list":cs_list})
elif request.method == "POST":
name = request.POST.get("username")
age = request.POST.get("age")
gender = request.POST.get("gender")
cs = request.POST.get("cs")
models.Students.objects.create(
name=name,
age=age,
gender=gender,
cs_id=cs
)
return redirect("/students.html")
def del_students(request):
nid = request.GET.get("nid")
models.Students.objects.filter(id=nid).delete()
return redirect("/students.html")
def edit_students(request):
if request.method == "GET":
nid = request.GET.get("nid")
obj = models.Students.objects.filter(id=nid).first() # 加first()转为对象才可在HTML中直接调用
cs_list = models.Classes.objects.all()
return render(request,"edit_students.html",locals())
elif request.method == "POST":
u = request.POST.get("username")
a = request.POST.get("age")
g = request.POST.get("gender")
c = request.POST.get("class_id")
nid = request.POST.get("id")
models.Students.objects.filter(id=nid).update(
name=u,
age=a,
gender=g,
cs_id=c
)
return redirect("/students.html")
二、HTML文件
增加学员
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h3>添加用户</h3>
<form action="/add_students.html" method="POST">
{% csrf_token %}
<p><input type="text" name="username" placeholder="用户名"></p>
<p><input type="text" name="age" placeholder="年龄"></p>
<p>
男:<input type="radio" name="gender" value="1"> {#name相等时互相排斥#}
女:<input type="radio" name="gender" value="0">
</p>
<p>
<select name="cs" id=""> {# 下拉框 cs为value值,用于回传 #}
{% for row in cs_list %}
<option value="{{row.id}}">{{row.name}}</option>
{% endfor %}
</select>
</p>
<input type="submit" value="提交">
</form>
</body>
</html>
编辑学员
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/edit_students.html" method="POST">
{% csrf_token %}
<p><input type="text" name="id" value="{{obj.id}}" style="display:none"></p>
<p><input type="text" name="username" value="{{obj.name}}"></p>
<p><input type="text" name="age" value="{{obj.age}}"></p>
<p>
{% if obj.gender %}
男:<input type="radio" name="gender" checked="checked" value="1"> {# 默认选择 #}
女:<input type="radio" name="gender" value="0">
{% else %}
男:<input type="radio" name="gender" value="1">
女:<input type="radio" name="gender" checked="checked" value="0">
{% endif %}
</p>
<p>
<select name="class_id" id="">
{% for row in cs_list %}
{% if row.id == obj.cs_id %} {# 判断关联ID相同,默认选中 #}
<option value="{{row.id}}" selected="selected">{{row.name}}</option>
{% else %}
<option value="{{row.id}}" >{{row.name}}</option>
{% endif %}
{% endfor %}
</select>
</p>
<input type="submit" value="提交">
</form>
</body>
</html>