Django--一对多表操作
今天还以一个学生管理系统为例,先通过pymysql这个模块,进行一对多表操作,有以下两种方式
- 新url的方式:直接新开一个页面进行操作
- ajax模态框的方式:在本页面通过模态框的方式进行操作
需求
- 对学生表进行增删改查
步骤
- 开始写功能
- 添加路由
- 设计模板
- 写对应的接口函数
添加路由映射关系
urlpatterns = [
# 新url方式
url(r'^students/', students),
url(r'^add_student/', add_student),
url(r'^del_student/', del_student),
url(r'^update_student/', update_student),
# ajax方式
url(r'^ajax_add_student/', ajax_add_student),
url(r'^ajax_update_student/', ajax_update_student),
]
学生表的增删改查
# students.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>学生表</title>
<style>
a {
color: black;
text-decoration: none;
}
.shadow {
position: fixed;
left: 0;
right: 0;
top: 0;
bottom: 0;
background-color: black;
opacity: 0.4;
display: none;
}
.add_model, .update_model {
position: fixed;
height: 300px;
500px;
left: 500px;
top: 100px;
background-color: white;
display: none;
}
.model {
margin-top: 20px;
margin-left: 40px;
}
</style>
</head>
<body>
<h2>学生表</h2>
<table border="1" cellspacing="0">
<tbody>
<tr>
<th>ID</th>
<th>姓名</th>
<th>年龄</th>
<th>班级</th>
<th>更新</th>
<th>删除</th>
</tr>
{% for stu in students %}
<tr>
<td>{{ stu.sid }}</td>
<td>{{ stu.name }}</td>
<td>{{ stu.age }}</td>
<td clsid="{{ stu.cid }}">{{ stu.cname }}</td>
<td>
<button><a href="/update_student/?id={{ stu.sid }}">更新</a></button>
<button class="ajax_update">ajax更新</button>
</td>
<td>
<button><a href="/del_student/?id={{ stu.sid }}" class="delete">删除</a></button>
{# <button class="ajax_delete">ajax删除</button>#}
</td>
</tr>
{% endfor %}
</tbody>
</table>
<br><br>
<button><a href="/add_student/" target="_blank">添加学生</a></button>
<button id="ajax_add">ajax添加学生</button>
</body>
</html>
# add_student.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>添加学生</title>
<style>
a {
color: black;
text-decoration: none;
}
</style>
</head>
<body>
<h2>增加学生</h2>
<form action="/add_student/" method="post">
姓名:<input type="text" name="sname"><br>
年龄:<input type="text" name="sage"><br>
<div style="margin-top: 2px;margin-bottom: 10px">
班级:<select name="cid" id="" style=" 166px; height: 21.5px">
{% for class in classes %}
<option value="{{ class.id }}">{{ class.cname }}</option>
{% endfor %}
</select>
</div>
<span style="color:red; font-size: 12px;">{{ data }}</span><br>
<span style="margin-left: 48px;"><input type="submit" value="添加"></span>
<span style="margin-left: 40px;"><button><a href="/students/">取消</a></button></span>
</form>
</body>
</html>
# uodate_student.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>学生信息更新</title>
<style>
a {
color: black;
text-decoration: none;
}
</style>
</head>
<body>
<h2>更新学生信息</h2>
<form action="/update_student/" method="post">
<input type="hidden" name="sid" value="{{ student.id }}">
姓名:<input type=" text" name="sname" value="{{ student.name }}"><br>
年龄:<input type="text" name="sage" value="{{ student.age }}"><br>
<div style="margin-top: 2px;margin-bottom: 10px">
班级:<select name="cid" id="" style=" 166px; height: 21.5px">
{% for class in classes %}
{% if student.cid == class.id %}
<option value="{{ class.id }}" selected>{{ class.cname }}</option>
{% else %}
<option value="{{ class.id }}">{{ class.cname }}</option>
{% endif %}
{% endfor %}
</select></div>
<span style="color:red; font-size: 12px;">{{ data }}</span><br>
<span style="margin-left: 48px;"><input type="submit" value="更新"></span>
<span style="margin-left: 40px;"><button><a href="/students/">取消</a></button></span>
</form>
</body>
</html>
# urls.py
# 获取学生信息
@deco
def students(request):
sql = 'select students.id as sid,name,age,classes.id as cid,cname from students left join classes on students.cid = classes.id order by sid'
students = mysql(sql)[0]
sql = 'select * from classes'
classes = mysql(sql)[0]
return render(request, 'students.html', {'students': students, 'classes': classes})
# 添加学生
@deco
def add_student(request):
sql = 'select * from classes'
classes = mysql(sql)[0]
if request.method == 'GET':
return render(request, 'add_student.html', {'classes': classes})
else:
sname = request.POST.get('sname')
age = request.POST.get('sage')
cid = request.POST.get('cid')
if not (sname and age):
data = "姓名年龄不能为空"
return render(request, 'add_student.html', {'data': data, 'classes': classes})
sql = 'select * from students where name=%s'
res = mysql(sql, (sname,))[0]
if res:
data = "姓名已存在"
return render(request, 'add_student.html', {'data': data, 'classes': classes})
sql = 'insert into students(name,age,cid) values(%s,%s,%s)'
mysql(sql, (sname, age, cid))
return redirect('/students/')
# 更新学生信息
@deco
def update_student(request):
sql = 'select * from classes'
classes = mysql(sql)[0]
if request.method == "GET":
id = request.GET.get('id')
# print(id)
s_sql = 'select * from students where id=%s'
student = mysql(s_sql, (id,))[0]
return render(request, 'update_student.html', {'student': student, 'classes': classes})
else:
id = request.POST.get('sid')
name = request.POST.get('sname')
age = request.POST.get('sage')
cid = request.POST.get('cid')
s_sql = 'select * from students where id=%s'
student = mysql(s_sql, (id,))[0]
if not (name and age):
data = "姓名或年龄不能为空"
return render(request, 'update_student.html', {'student': student, 'classes': classes, 'data': data})
sql = 'select * from students where name=%s and age=%s and cid=%s'
res = mysql(sql, (name, age, cid))[0]
if res:
data = "学生信息已存在"
return render(request, 'update_student.html', {'student': student, 'classes': classes, 'data': data})
sql = 'update students set name=%s,age=%s,cid=%s where id=%s'
mysql(sql, (name, age, cid, id))
return redirect('/students/')
# 删除学生信息
@deco
def del_student(request):
id = request.GET.get('id')
# print(id)
sql = "delete from students where id=%s"
mysql(sql, (id,))
return redirect('/students/')
ajax更新和添加
# students.html
<!--直接加在students.html页面里面-->
{# 遮罩层 #}
<div class="shadow"></div>
{# 弹出框层 #}
{# 增加学生 #}
<div class="add_model">
{# <input type="hidden" name="class_id">#}
<div class="model">
名字:<input type="text" name="name" id="add_student"><br>
年龄:<input type="text" name="age" id="add_age"><br>
<div style="margin-top: 2px;margin-bottom: 2px">
班级:<select name="add_cid" id="add_cid" style=" 166px; height: 21.5px">
{% for class in classes %}
<option value="{{ class.id }}">{{ class.cname }}</option>
{% endfor %}
</select></div>
<span id="add_error" style="color:red; font-size: 12px; margin-bottom: 10px;"></span><br>
<button id="add" style="margin-left: 48px;">添加</button>
<button class="add_cancel" style="margin-left: 40px;">取消</button>
</div>
</div>
{# 更新学生 #}
<div class="update_model">
<div class="model">
<input type="hidden" name="sid" id="up_sid">
姓名:<input type="text" name="name" id="up_name"><br>
年龄:<input type="text" name="age" id="up_age">
<div style="margin-top: 2px;margin-bottom: 2px">
班级:<select name="up_cid" id="up_cid" style=" 166px; height: 21.5px">
{% for class in classes %}
<option value="{{ class.id }}">{{ class.cname }}</option>
{% endfor %}
</select>
</div>
<span id="up_error" style="color:red; font-size: 12px; margin-bottom: 10px;"></span><br>
<button id="update" style="margin-left: 48px;">更新</button>
<button class="up_cancel" style="margin-left: 48px;">取消</button>
</div>
</div>
{# CDN导入jQuery #}
<script
src="http://code.jquery.com/jquery-1.12.4.min.js"
integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
crossorigin="anonymous"></script>
{# 删除学生 #}
<script>
$('.delete').click(function () {
res = window.confirm('是否删除学生');
return res;
});
</script>
{# 增加学生 #}
<script>
$('#ajax_add').click(function () {
$('.shadow, .add_model').css('display', 'block');
{#$('.shadow, .add_model').show()#}
});
$('.add_cancel').click(function () {
$('.shadow, .add_model').hide();
window.location.href='/students/'
});
$('#add').click(function () {
var name = $('#add_student').val();
var age = $('#add_age').val();
var cid = $('#add_cid').val();
{#console.log(classname);#}
$.ajax({
type: 'POST',
url: '/ajax_add_student/',
data: {'name': name,'age':age,'cid':cid},
success: function (data) {
var res = JSON.parse(data);
if (res['code'] == 10000) {
alert(res['msg']);
window.location.href = '/students/';
} else {
$('#add_error').text(res['msg']);
}
}
})
});
</script>
{# 更新学生 #}
<script>
$('.ajax_update').click(function () {
$('.shadow, .update_model').show();
var info = $(this).parent().prevAll();
{#console.log(info)#}
var age = info[1].innerText;
var name = info[2].innerText;
var id = info[3].innerText;
var cid = $(info[0]).attr('clsid');
$('#up_age').val(age);
$('#up_name').val(name);
$('#up_sid').val(id);
$('#up_cid').val(cid);
});
$('.up_cancel').click(function () {
$('.shadow, .update_model').hide();
window.location.href = '/students/';
});
$('#update').click(function () {
var name = $('#up_name').val();
var age = $('#up_age').val();
var id = $('#up_sid').val();
var cid = $('#up_cid').val();
{#console.log(classname,id);#}
$.ajax({
type: 'POST',
url: '/ajax_update_student/',
data: {'id':id,'name': name, 'age': age,'cid': cid},
success: function (data) {
var res = JSON.parse(data);
if (res['code'] == 10000) {
alert(res['msg']);
window.location.href = '/students/';
} else {
$('#up_error').text(res['msg']);
}
}
})
});
</script>
# urls.py
# ajax增加学生
@deco
def ajax_add_student(request):
name = request.POST.get('name')
age = request.POST.get('age')
cid = request.POST.get('cid')
res = {'code': None, 'msg': None}
if not (name and age):
res['code'] = 10001
res['msg'] = '姓名年龄不能为空'
return HttpResponse(json.dumps(res))
sql = 'select * from students where name=%s and age=%s and cid=%s '
resp = mysql(sql, (name, age, cid))[0]
if resp:
res['code'] = 10001
res['msg'] = f'学生--{name}--已存在'
return HttpResponse(json.dumps(res))
sql = 'insert into students(name,age,cid) values(%s,%s,%s)'
mysql(sql, (name, age, cid))
res['code'] = 10000
res['msg'] = f'学生--{name}--信息添加成功'
return HttpResponse(json.dumps(res))
# ajax更新学生
@deco
def ajax_update_student(request):
id = request.POST.get('id')
name = request.POST.get('name')
age = request.POST.get('age')
cid = request.POST.get('cid')
res = {'code': None, 'msg': None}
if not (name and age):
res['code'] = 10001
res['msg'] = '姓名年龄不能为空'
return HttpResponse(json.dumps(res))
sql = 'select * from students where name=%s and age=%s and cid=%s '
resp = mysql(sql, (name, age, cid))[0]
if resp:
res['code'] = 10001
res['msg'] = f'学生--{name}--已存在'
return HttpResponse(json.dumps(res))
sql = "update students set name=%s,age=%s,cid=%s where id=%s"
mysql(sql, (name, age, cid, id))
res['code'] = 10000
res['msg'] = f'学生--{name}--信息更新成功'
return HttpResponse(json.dumps(res))