Django小项目练习
Django学生管理系统
urlpatterns = [
url(r'^admin/', admin.site.urls), url(r'^class_list/', views.class_list),
url(r'^add_class/', views.add_class),
url(r'^edit_class/(\d+)/', views.edit_class), url(r'^student_list/', views.student_list),
url(r'^add_student/', views.add_student),
url(r'^edit_student/(\d+)/', views.edit_student), url(r'^teacher_list/', views.teacher_list),
url(r'^add_teacher/', views.add_teacher),
url(r'^edit_teacher/(\d+)/', views.edit_teacher), ]
urls.py
from django.shortcuts import render,redirect,HttpResponse
from app01 import models
from django.forms import Form
from django.forms import fields
from django.forms import widgets
from django.forms import models as form_model
from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator class ClassForm(Form):
title = fields.RegexField('全栈\d+') def class_list(request):
cls_list = models.Classes.objects.all()
return render(request,'class_list.html',{'cls_list':cls_list}) def add_class(request):
if request.method == "GET":
obj = ClassForm()
return render(request,'add_class.html',{'obj': obj})
else:
obj = ClassForm(request.POST)
if obj.is_valid():
# obj.cleaned_data # 字典
# 数据库创建一条数据
# print(obj.cleaned_data)
# models.Classes.objects.create(title=obj.cleaned_data['tt']) models.Classes.objects.create(**obj.cleaned_data)
return redirect('/class_list/')
return render(request,'add_class.html',{'obj': obj}) def edit_class(request,nid):
if request.method == "GET":
row = models.Classes.objects.filter(id=nid).first()
# 让页面显示初始值
# obj = ClassForm(data={'title': 'asdfasdfasdfas'})
obj = ClassForm(initial={'title': row.title})
return render(request,'edit_class.html',{'nid': nid,'obj':obj})
else:
obj = ClassForm(request.POST)
if obj.is_valid():
print(obj.cleaned_data)
models.Classes.objects.filter(id=nid).update(**obj.cleaned_data)
return redirect('/class_list/')
return render(request,'edit_class.html',{'nid': nid,'obj':obj}) class StudentForm(Form):
name = fields.CharField(
min_length=2,
max_length=6,
widget=widgets.TextInput(attrs={'class': 'form-control'})
)
email = fields.EmailField(widget=widgets.TextInput(attrs={'class': 'form-control'}))
age = fields.IntegerField(min_value=18,max_value=25,widget=widgets.TextInput(attrs={'class': 'form-control'}))
cls_id = fields.IntegerField(
# widget=widgets.Select(choices=[(1,'上海'),(2,'北京')])
widget=widgets.Select(choices=models.Classes.objects.values_list('id','title'),attrs={'class': 'form-control'})
) def student_list(request): stu_list = models.Student.objects.all()
return render(request,'student_list.html',{'stu_list':stu_list}) def add_student(request):
if request.method == "GET":
obj = StudentForm()
return render(request,'add_student.html',{'obj':obj})
else:
obj = StudentForm(request.POST)
if obj.is_valid():
models.Student.objects.create(**obj.cleaned_data)
return redirect('/student_list/')
return render(request,'add_student.html',{'obj':obj}) def edit_student(request,nid):
if request.method == "GET":
row = models.Student.objects.filter(id=nid).values('name','email','age','cls_id').first()
obj = StudentForm(initial=row)
return render(request,'edit_student.html',{'nid':nid,'obj': obj})
else:
obj = StudentForm(request.POST)
if obj.is_valid():
models.Student.objects.filter(id=nid).update(**obj.cleaned_data)
return redirect('/student_list/')
return render(request,'edit_student.html',{'nid':nid,'obj': obj}) class TeacherForm(Form):
tname = fields.CharField(min_length=2)
xx = fields.MultipleChoiceField(
# choices=models.Classes.objects.values_list("id","title"),
widget=widgets.SelectMultiple
)
def __init__(self,*args,**kwargs):
super(TeacherForm,self).__init__(*args,**kwargs)
self.fields["xx"].choices =models.Classes.objects.values_list("id","title") def teacher_list(request):
tea_list = models.Teacher.objects.all()
# tea_class = tea_list.c2t.all()
# print(tea_class)
return render(request,"teacher_list.html",{"tea_list":tea_list}) def add_teacher(request):
if request.method == "GET":
obj = TeacherForm()
# # print(obj.xx)
# print(obj.tname)
return render(request,"add_teacher.html",{"obj":obj})
else:
obj = TeacherForm(request.POST)
if obj.is_valid():
print(obj.cleaned_data)
xx = obj.cleaned_data.pop("xx")
row = models.Teacher.objects.create(**obj.cleaned_data)
row.c2t.add(*xx)
return redirect("/teacher_list/")
return render(request,"add_teacher.html",{"obj":obj}) def edit_teacher(request,tid):
if request.method == "GET":
row = models.Teacher.objects.filter(id=tid).first()
class_ids = row.c2t.values_list("id")
print(class_ids)
print(list(zip(*class_ids)))
id_list = list(zip(*class_ids))[0] if list(zip(*class_ids)) else [] obj = TeacherForm(initial={'tname':row.tname,'xx':id_list})
return render(request,'edit_teacher.html',{'obj':obj,"tid":tid})
else: obj = TeacherForm(request.POST)
if obj.is_valid():
print(obj.cleaned_data) xx = obj.cleaned_data.pop("xx")
row = models.Teacher.objects.create(**obj.cleaned_data)
row.c2t.add(*xx)
return redirect("/teacher_list/")
else:
print("")
return render(request, 'edit_teacher.html', {'obj': obj, "tid": tid})
View.py
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>班级列表</h1>
<div>
<a href="/add_class/">添加</a>
</div>
<ul>
{% for row in cls_list %}
<li>{{ row.title }} <a href="/edit_class/{{ row.id }}/">编辑</a> </li>
{% endfor %}
</ul>
</body>
</html>
class_list.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>添加班级</h1>
<form method="POST" action="/add_class/" novalidate>
{% csrf_token %}
{{ obj.title }} {{ obj.errors.title.0 }}
<input type="submit" value="提交" />
</form>
</body>
</html>
add_class.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>编辑班级</h1>
<form method="POST" action="/edit_class/{{ nid }}/">
{% csrf_token %}
<p>
{{ obj.title }} {{ obj.errors.title.0 }}
</p>
<input type='submit' value="提交" />
</form>
</body>
</html>
edit_class.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>学生列表</h1>
<a href="/add_student/">添加</a>
<ul>
{% for row in stu_list %}
<li>{{ row.name }}-{{ row.email }}-{{ row.age }}-{{ row.cls_id }}-{{ row.cls.title }} <a href="/edit_student/{{ row.id }}/">编辑</a></li>
{% endfor %}
</ul>
</body>
</html>
student_list.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>添加学生</h1>
<form action="/add_student/" method="POST">
{% csrf_token %}
<p>
学生名称:{{ obj.name }}
</p>
<p>
学生邮箱:{{ obj.email }}
</p>
<p>
学生年龄:{{ obj.age }}
</p>
<p>
班级:{{ obj.cls_id }}
</p>
<input type="submit" value="提交" />
</form>
</body>
</html>
add_student.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.css"/>
</head>
<body> <div style="width: 500px;margin: 0 auto;">
<form class="form-horizontal" method="POST" action="/edit_student/{{ nid }}/">
{% csrf_token %}
<div class="form-group">
<label class="col-sm-2 control-label">姓名:</label> <div class="col-sm-10">
{{ obj.name }}
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">邮箱:</label> <div class="col-sm-10">
{{ obj.email }}
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">年龄:</label> <div class="col-sm-10">
{{ obj.age }}
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">班级:</label> <div class="col-sm-10">
{{ obj.cls_id }}
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" class="btn btn-default" value="提交" />
</div>
</div>
</form>
</div>
</body>
</html>
edit_student.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>老师列表</h1>
<div>
<a href="/add_teacher/">增加</a>
</div>
<table border="">
<thead>
<tr>
<th>ID</th>
<th>老师名称</th>
<th>任教老师</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for row in tea_list %}
<tr>
<td>{{ row.id }}</td>
<td>{{ row.tname }}</td>
<td>
{% for row in row.c2t.all %}
{{ row.title }}
{% endfor %} </td>
<td>
<a href="/edit_teacher/{{ row.id }}">编辑</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
teacher.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body> <form action="/add_teacher/" method="POST">
{% csrf_token %}
<p>
姓名: {{ obj.tname }}
</p>
<p>
班级 {{ obj.xx }}
</p>
<input type="submit" value="提交">
</form> </body>
</html>
add_teacher.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h3>编辑老师</h3> <form action="/edit_teacher/{{ tid }}/" novalidate method="POST">
{% csrf_token %}
<p>
{{ obj.tname }}
</p>
<p>
{{ obj.xx }}
</p>
<input type="submit" value="提交">
</form>
</body>
</html>
edit_teacheer.html
Django学生管理系统(使用AJAX实现模态对话框)
1. 一对一 班级 模态增加 编辑
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style> .hide{
display: none;
}
.shadow{
position: fixed;
left: 0;
top: 0;
right: 0;
bottom: 0;
background-color: black;
opacity: 0.4;
z-index: 999;
}
.modal{
z-index: 1000;
position: fixed;
left: 50%;
top: 50%;
height: 300px;
width: 400px;
background-color: white;
margin-left: -200px;
margin-top: -150px;
} .del_class{
z-index: 1001;
position: fixed;
left: 50%;
top: 50%;
height: 150px;
width: 300px;
background-color: white;
margin-left: -150px;
margin-top: -75px;
} .edit_class{
z-index: 1002;
position: fixed;
left: 50%;
top: 50%;
height: 150px;
width: 300px;
background-color: white;
margin-left: -150px;
margin-top: -75px;
}
</style>
</head>
<body> <h1>班级列表</h1> <div>
<a onclick="showModal();">模态框增加</a>
</div> <table border="1px">
<thead>
<tr>
<td>ID</td>
<td>班级名称</td> <td>模态操作</td>
</tr>
</thead>
<tbody>
{% for row in data %}
<tr>
<td>{{ row.cid }}</td>
<td>{{ row.title }}</td> <td>
<a onclick="modelEdit(this)">编辑</a>
<a onclick="DelClass({{ row.cid }})">删除</a>
</td>
</tr>
{% endfor %}
</tbody>
</table> {# 遮罩#}
<div id="shadow" class="shadow hide"></div> {# 增加#}
<div id="addmodal" class="modal hide">
<p>班级名称:
<input id="addtitle" type="text" name="title" />
</p>
<input type="button" value="提交" onclick="AjaxSend();" /><span id="errormsg"></span>
<input type="button" value="取消" onclick="cancleModal();" />
</div> {# 编辑#}
<div id="editModal" class="modal hide">
<h3>编辑</h3>
<input id="editId" type="text" name="id" style="display: none">
<p>班级名称<input id="editTitle" type="text" name="title" ></p>
<input type="button" value="提交" onclick="editAjaxSend()"><span id="errormsg"></span>
<input type="button" value="取消" onclick="cancleModal()">
</div> <script src="/static/jquery-3.2.1.js"></script> <script> {# 增加#}
function showModal() {
$("#addmodal,#shadow").removeClass("hide");
} function AjaxSend() {
title=$("#addtitle").val();
$.ajax({
url: '/motai_add_class/',
type: 'POST',
data: {'title': title},
success: function(arg){
arg = JSON.parse(arg);
if(arg.status){
location.reload();
}else{
alert(arg.message);
}
}
})
} {# 编辑#}
function modelEdit(self) {
$("#editModal,#shadow").removeClass("hide"); var title=$(self).parent().prevAll().eq(0).text();
var id=$(self).parent().prevAll().eq(1).text();
$("#editTitle").val(title);
$("#editId").val(id);
} function editAjaxSend() {
id = $("#editId").val();
title = $("#editTitle").val();
$.ajax({
url: '/modal_edit_class/',
type: 'POST',
data: {"id":id,"title": title},
success: function(arg){
arg = JSON.parse(arg);
if(arg.status){
location.reload();
}else{
alert(arg.message);
}
}
})
} {# 隐藏#}
function cancleModal() {
$("#shadow").addClass("hide");
$("#addmodal").addClass("hide");
$("#editModal").addClass("hide")
} </script> </body>
</html>
classes.html
def classes(request):
data = sqlheper.get_list("select cid,title from class",[])
return render(request, "classes.html", {"data": data}) def motai_add_class(request):
ret = {'status': True, 'message': None}
title = request.POST.get('title')
try:
nid = request.POST.get('nid')
content = request.POST.get('content')
sqlheper.motify_sql('insert into class(title) values(%s)',[title,])
except Exception as e:
ret['status'] = False
ret['message'] = "处理异常" return HttpResponse(json.dumps(ret)) def modal_edit_class(request):
print(request.POST)
ret = {'status': True, 'message':None}
try:
id = request.POST.get('id')
title = request.POST.get('title')
sqlheper.motify_sql('update class set title=%s where cid=%s',[title,id,])
except Exception as e:
ret['status'] = False
ret['message'] = "处理异常" return HttpResponse(json.dumps(ret))
views.py
2.一对多 学生班级 模态增加 编辑
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.hide{
display: none;
}
.shadow{
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
background-color: black;
z-index: 999;
opacity: 0.4;
}
.Modal{
position: fixed;
top: 50%;
left: 50%;
width: 400px;
height: 300px;
margin-left: -200px;
margin-top: -150px;
z-index: 1000;
background-color: white;
}
</style>
</head>
<body> <h1>班级学员</h1> <div>
<a id="addStudent">模态框增加</a>
</div> <table border="1px">
<thead>
<tr>
<td>学员名称</td>
<td>学生名称</td>
<td>班级名称</td>
<td>模态操作</td>
</tr>
</thead>
<tbody>
{% for row in student_list %}
<tr>
<td>{{ row.sid }}</td>
<td>{{ row.name }}</td>
<td clsId="{{ row.class_id }}">{{ row.title }}</td>
<td>
<a class="btn-edit">编辑</a>
<a >删除</a>
</td>
</tr>
{% endfor %}
</tbody>
</table> <div id="shadow" class="shadow hide"></div> {#增加#}
<div id="addModal" class="Modal hide"> <p>学生名称:
<input id="add_name" type="text" name="add_name">
</p>
<p>学生性别:
<input id="add_sex" type="text" name="add_sex">
</p>
<p>班级名称:
<select id="add_classId" name="add_classId">
{% for row in class_list %}
<option value="{{ row.cid }}">{{ row.title }}</option>
{% endfor %}
</select>
</p> <input id="btnAdd" type="button" value="提交"><span id="addError"></span>
<input id="btnCancle" type="button" value="取消"> </div> {#编辑#}
<div id="editModal" class="Modal hide">
<h3>编辑学生信息</h3>
<p>
姓名:<input id="editName" type="text" name="name" placeholder="姓名" />
<input type="text" id="editId" style="display: none" />
</p>
<p>
班级:
<select id="editClassId" name="classId">
{% for row in class_list %}
<option value="{{ row.cid }}">{{ row.title }}</option>
{% endfor %}
</select>
</p>
<input id="btnEdit" type="button" value="更新" />
<span id="editError" style="color: red;"></span>
<input id="btnCancle" type="button" value="取消" />
</div> <script src="/static/jquery-3.2.1.js"></script> <script> $(function () { {# 增加#} $("#addStudent").click(function () {
$("#shadow,#addModal").removeClass("hide");
}); $("#btnCancle").click(function () {
$("#shadow,#addModal").addClass("hide");
$("#editModal").addClass("hide");
}); $("#btnAdd").click(function () {
var add_name=$("#add_name").val();
var add_age=$("#add_sex").val();
var add_classId=$("#add_classId").val();
$.ajax({
url:"/motai_add_student/",
type:"POST",
data:{"add_name":add_name,"add_age":add_age,"add_classId":add_classId},
success:function (arg) {
arg = JSON.parse(arg);
if (arg.status){
location.reload();
}else {
$("#addError").text(arg.message);
}
}
}) }); {# 编辑 #}
$('.btn-edit').click(function(){
$('#shadow,#editModal').removeClass('hide'); var tds = $(this).parent().prevAll();
var studentId = $(tds[2]).text();
var studentName = $(tds[1]).text();
var classId = $(tds[0]).attr('clsid'); console.log(studentId,studentName,classId); $('#editId').val(studentId);
$('#editName').val(studentName);
$('#editClassId').val(classId);
}); $('#btnEdit').click(function(){
$.ajax({
url:'/motai_edit_student/',
type: 'POST',
data: {'sid': $('#editId').val(), 'name':$('#editName').val(),'class_id': $('#editClassId').val()},
dataType: 'JSON', //JSON.parse(arg)
success:function(arg){
if(arg.status){
location.reload();
}else{
$('#editError').text(arg.message);
}
}
})
});
}) </script> </body>
</html>
student.html
def student(request):
student_list = sqlheper.get_list("select student.sid,student.name,student.class_id,class.title from student left join class on student.class_id=class.cid",[]) class_list = sqlheper.get_list("select cid,title from class",[]) return render(request, "student.html", {"student_list":student_list, "class_list":class_list}) def motai_add_student(request):
print(request.POST)
ret = {"status":True,"message":None}
try:
name = request.POST.get("add_name")
age = request.POST.get("add_age")
classId = request.POST.get("add_classId") sqlheper.motify_sql("insert into student(name,age,class_id) values(%s,%s,%s)",[name,age,classId,])
except Exception as e:
ret["status"] = False
ret["message"] = str(e)
return HttpResponse(json.dumps(ret)) def motai_edit_student(request):
ret = {'status': True,'message': None}
try: print(request.POST)
sid = request.POST.get('sid')
name = request.POST.get('name')
class_id = request.POST.get('class_id')
sqlheper.motify_sql('update student set name=%s,class_id=%s where sid=%s',[name,class_id,sid,])
except Exception as e:
ret['status'] = False
ret['message'] = str(e)
return HttpResponse(json.dumps(ret))
views.py
3.多对多 老师 班级 模态增加 编辑
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.hide{
display: none;
}
.shadow{
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
background-color: black;
z-index: 999;
opacity: 0.4;
}
.Modal{
position: fixed;
top: 50%;
left: 50%;
width: 400px;
height: 300px;
margin-left: -200px;
margin-top: -150px;
z-index: 1000;
background-color: white;
}
</style>
</head>
<body> <h1>老师 班级管理</h1> <div> <a id="addModal">模态框增加</a>
</div> <table border="solid" >
<thead>
<tr>
<td>ID</td>
<td>老师名称</td>
<td>班级名称</td>
<td>操作</td>
</tr>
</thead>
<tbody>
{% for row in teacher_list %}
<tr>
<td>{{ row.tid }}</td>
<td>{{ row.name }}</td>
<td>
{% for item in row.titles %}
{{ item }}
{% endfor %}
</td>
<td>
<a class="editModal">编辑</a>
<a class="delModal">删除</a>
</td>
</tr>
{% endfor %}
</tbody> </table> <div id="shadow" class="shadow hide"></div> <div id="add_tea_cls" class="Modal hide"> <p>老师名称:
<input id="add_name" type="text" name="add_name">
</p> <p>班级名称:
<select id="add_classId" name="add_classId" multiple>
{% for row in class_list %}
<option value="{{ row.cid }}">{{ row.title }}</option>
{% endfor %}
</select>
</p>
<input id="btnAdd" type="button" value="提交"><span id="addError"></span>
<input id="btnCancle" type="button" value="取消"> </div> <div id="edit_tea_cls" class="Modal hide"> <p>老师名称:
<input id="add_name" type="text" name="add_name">
</p> <p>班级名称:
<select id="add_classId" name="add_classId" multiple>
{% for row in class_list %}
<option value="{{ row.cid }}">{{ row.title }}</option>
{% endfor %}
</select>
</p>
<input id="btnEdit" type="button" value="提交"><span id="addError"></span>
<input id="cacleEdit" type="button" value="取消"> </div> <script src="/static/jquery-3.2.1.js"></script> <script> $(function () { {# 增加#}
$("#addModal").click(function () {
$("#shadow,#add_tea_cls").removeClass("hide");
}); $("#btnCancle").click(function () {
$("#shadow,#add_tea_cls").addClass("hide");
}); $("#btnAdd").click(function () {
tname=$("#add_name").val();
class_list=$("#add_classId").val();
console.log(class_list)
$.ajax({
url:"/new_teacher/",
type:"POST",
data:{"tname":tname,"class_list":class_list},
success:function (arg) {
arg = JSON.parse(arg);
if (arg.status){
location.reload();
}else {
$("#addError").text(arg.message);
}
}
})
}); {# 编辑#}
$(".editModal").click(function () {
$("#shadow").removeClass("hide");
$("#edit_tea_cls").removeClass("hide");
}); $("#cacleEdit").click(function () {
$("#shadow,#edit_tea_cls").addClass("hide");
}); }) </script> </body>
</html>
teacher.html
def teacher(request): teacher_list=sqlheper.get_list("""
select teacher.tid as tid,teacher.name,class.title from teacher
left join teacher_class on teacher_class.teacher_id=teacher.tid
left join class on class.cid=teacher_class.class_id""",[])
# print(teacher_list)
result = {}
for row in teacher_list:
tid = row["tid"]
if tid in result:
result[tid]["titles"].append(row["title"])
else:
result[tid] = {"tid":row["tid"],"name":row["name"],"titles":[row["title"],]} class_list = sqlheper.get_list("select cid,title from class",[]) return render(request, "teacher.html_模态增加 老师班级", {"teacher_list":result.values(), "class_list":class_list}) ###模态增加
def new_teacher(request):
print(request.POST)
ret = {'status': True, 'message': None}
try:
class_list=request.POST.getlist("class_list[]")
tname=request.POST.get("tname")
print(class_list)
print(tname)
teacher_id=sqlheper.get_IncrementId("insert into teacher(name) values(%s)",[tname,])
for item in class_list:
sqlheper.motify_sql("insert into teacher_class(teacher_id,class_id) values(%s,%s)",[teacher_id,item,])
except Exception as e:
ret['status'] = False
ret['message'] = str(e)
return HttpResponse(json.dumps(ret))
views.py
4.多对多 老师 班级 新url 增加 编辑
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title> </head>
<body> <h1>老师 班级管理</h1> <div> <a href="/add_page_teacher/">增加</a>
</div> <table border="solid" >
<thead>
<tr>
<td>ID</td>
<td>老师名称</td>
<td>班级名称</td>
<td>操作</td>
</tr>
</thead>
<tbody>
{% for row in teacher_list %}
<tr>
<td>{{ row.tid }}</td>
<td>{{ row.name }}</td>
<td>
{% for item in row.titles %}
{{ item }}
{% endfor %}
</td>
<td>
<a href="/edit_page_teacher/?tid={{ row.tid }}">编辑</a>
<a >删除</a>
</td>
</tr>
{% endfor %}
</tbody> </table> </body>
</html>
teacher.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body> <h1>增加老师</h1> <form action="/add_teacher/" method="POST">
<p>老师名称: <input type="text" name="name"></p>
<input type="submit">
</form> </body>
</html>
add_page_teacher.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body> <h3>编辑老师班级</h3> <form action="/edit_page_teacher/?tnid={{ tname.tid }}" method="post"> <p>老师名称:<input type="text" name="name" value="{{ tname.name }}"></p> <p>班级名称:
<select name="class_ids" multiple size="">
{% for item in class_list %}
{% if item.cid in class_ids %}
<option selected value="{{ item.cid }}">{{ item.title }}</option>
{% else %}
<option value="{{ item.cid }}">{{ item.title }}</option>
{% endif %}
{% endfor %}
</select> <p><input type="submit" value="提交"></p>
</p> </form> </body>
</html>
edit_page_teacher.html
###网页显示
def teacher(request): teacher_list=sqlheper.get_list("""
select teacher.tid as tid,teacher.name,class.title from teacher
left join teacher_class on teacher_class.teacher_id=teacher.tid
left join class on class.cid=teacher_class.class_id""",[])
# print(teacher_list)
result = {}
for row in teacher_list:
tid = row["tid"]
if tid in result:
result[tid]["titles"].append(row["title"])
else:
result[tid] = {"tid":row["tid"],"name":row["name"],"titles":[row["title"],]} class_list = sqlheper.get_list("select cid,title from class",[]) return render(request, "teacher.html", {"teacher_list":result.values(), "class_list":class_list}) ###网页增加
def add_page_teacher(request):
if request.method=="GET":
obj = sqlheper.SqlHelper()
class_list = obj.get_list("select cid,title from class",[])
obj.close()
return render(request,"add_page_teacher.html",{"class_list":class_list})
else: name = request.POST.get("name")
obj = sqlheper.SqlHelper()
teacher_id = obj.get_lastrowid("insert into teacher(name) values(%s)",[name,])
obj.close() class_ids = request.POST.getlist("class_ids")
print(class_ids) data_list = []
for cls_id in class_ids:
temp = (teacher_id, cls_id,)
data_list.append(temp) obj = sqlheper.SqlHelper()
obj.multiple_modify('insert into teacher_class(teacher_id,class_id) values(%s,%s)', data_list)
obj.close()
return redirect('/teacher/') ###网页编辑
def edit_page_teacher(request):
if request.method=="GET":
teacher_id = request.GET.get("tid")
obj = sqlheper.SqlHelper()
tname = obj.get_one("select tid,name from teacher where tid=%s",[teacher_id,]) class_list = obj.get_list("select cid,title from class",[]) class_ids = obj.get_list("select class_id from teacher_class where teacher_id =%s",[teacher_id,])
obj.close() temp = []
for i in class_ids:
temp.append(i['class_id']) return render(request,"edit_page_teacher.html",{
"tname":tname,
"class_list":class_list,
"class_ids":temp,
})
else:
tid=request.GET.get("tnid")
name=request.POST.get("name")
class_ids=request.POST.getlist("class_ids") obj = sqlheper.SqlHelper()
obj.modify("update teacher set name=%s where tid=%s",[name,tid,])
obj.modify('delete from teacher_class where teacher_id=%s',[tid,])
data_list = []
for cls_id in class_ids:
temp = (tid,cls_id)
data_list.append(temp)
obj.multiple_modify('insert into teacher_class(teacher_id,class_id) values(%s,%s)',data_list)
obj.close()
return redirect('/teacher/')
views.py
5.多对多 老师 班级 模态 增加 编辑
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.hide{
display: none;
}
.shadow{
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
background-color: black;
z-index: 999;
opacity: 0.4;
}
.loading{
position: fixed;
width: 32px;
height: 32px;
left: 50%;
top:50%;
margin-left: -16px;
margin-top: -16px;
background-color: rebeccapurple;
background-image: url("/static/images/loading.gif") ;
background-size: 100%; }
.Modal{
position: fixed;
top: 50%;
left: 50%;
width: 400px;
height: 300px;
margin-left: -200px;
margin-top: -150px;
z-index: 1000;
background-color: white;
}
</style>
<link rel="stylesheet" href="/static/plugins/bootstrap-3.3.7-dist/css/bootstrap.css">
<link rel="stylesheet" href="/static/plugins/font-awesome-4.7.0/css/font-awesome.css">
</head>
<body> <h1 >老师 班级管理</h1> <div class="btn btn-success"> <a id="addModal">模态框增加</a>
</div> <table border="solid" class="table table-striped">
<thead>
<tr>
<td>ID</td>
<td>老师名称</td>
<td>班级名称</td>
<td>操作</td>
</tr>
</thead>
<tbody>
{% for row in teacher_list %}
<tr>
<td>{{ row.tid }}</td>
<td>{{ row.name }}</td>
<td>
{% for item in row.titles %}
{{ item }}
{% endfor %}
</td>
<td>
<a class="editModal">编辑</a>
<a class="delModal">删除</a>
</td>
</tr>
{% endfor %}
</tbody> </table> <div id="shadow" class="shadow hide"></div> <div id="loading" class="loading hide"></div> <div id="add_tea_cls" class="Modal hide"> <p>老师名称:
<input id="add_name" type="text" name="add_name">
</p> <p>班级名称:
<select id="add_classId" name="add_classId" multiple size=""> </select>
</p>
<input id="btnAdd" type="button" value="提交"><span id="addError"></span>
<input id="btnCancle" type="button" value="取消"> </div> <div id="edit_tea_cls" class="Modal hide">
<input type="text" id="hide_id" style="display: none"> <p>老师名称:
<input id="edit_name" type="text" name="add_name">
</p> <p>班级名称:
<select id="edit_classId" name="edit_classId" multiple size=""> </select>
</p>
<input id="btnEdit" type="button" value="提交"><span id="addError"></span>
<input id="cacleEdit" type="button" value="取消"> </div> <script src="/static/jquery-3.2.1.js"></script> <script> $(function () { {# 增加#}
$("#addModal").click(function () {
$("#shadow,#loading").removeClass("hide");
$.ajax({
url:"/get_all_class/",
type:"GET",
dataType:"JSON",
success:function (arg) {
$.each(arg,function (i,row) {
var tag = $("<option>"); /*var tag = document.createElement('option');*/
tag.text(row.title); /*tag.innerHTML = row.title;*/
tag.prop("value",row.cid);
$("#add_classId").append(tag); /*tag.setAttribute('value',row.id);*/
});
$('#loading').addClass('hide');
$('#add_tea_cls').removeClass('hide');
}
})
}); $("#btnCancle").click(function () {
$("#shadow,#add_tea_cls").addClass("hide");
}); $("#btnAdd").click(function () {
var tname=$("#add_name").val();
var class_list=$("#add_classId").val();
console.log(class_list);
$.ajax({
url:"/new_teacher/",
type:"POST",
data:{"tname":tname,"class_list":class_list},
dataType:"JSON",
traditional: true, // 如果提交的数据的值有列表,则需要添加此属性
success:function (arg) { if (arg.status){
location.reload();
}else {
alert(arg.message);
}
}
})
}); {# 编辑#}
$(".editModal").click(function () {
$("#shadow,#loading").removeClass("hide");
var ids=$(this).parent().prevAll()[2];
var id=$(ids).text();
$("#hide_id").val(id);
$.ajax({
url: "/edit_tea_cls/",
type: "POST",
dataType: "JSON",
data:{"id":id},
success: function (arg) { class_list = arg[0];
teacher_info = arg[1];
class_lds = arg[2];
console.log(class_lds);
$("#edit_classId").empty();
$.each(class_list, function (i, row) {
var tag = $("<option>");
tag.text(row.title);
tag.prop("value", row.cid); if(class_lds.indexOf(row.cid) == -1){
$("#edit_classId").append(tag);
}else {
tag.prop("selected","selected");
$("#edit_classId").append(tag);
}
});
$("#edit_name").val(teacher_info["name"]); $('#loading').addClass('hide');
$('#edit_tea_cls').removeClass('hide');
}
}); $("#cacleEdit").click(function () {
$("#shadow,#edit_tea_cls").addClass("hide");
});
}) {# 编辑提交#}
$("#btnEdit").click(function () {
var tid= $("#hide_id").val();
var name = $("#edit_name").val();
var class_ids = $("#edit_classId").val();
$.ajax({
url:"/modal_edit_teacher/",
type:"post",
dataType:"JSON",
traditional:true,
data:{"tid":tid,"name":name,"del_class_id":del_class_id},
$.ajax({
url:"/modal_edit_teacher/",
type:"post",
dataType:"JSON",
traditional:true,
data:{"tid":tid,"name":name,"class_ids":class_ids},
success:function (arg) {
if (arg.status){
location.reload();
}else {
alert("")
}
}
})
})
})
}) </script> </body>
</html>
teacher.html
#显示
def teacher(request): tk = request.COOKIES.get("ticket")
if not tk:
return redirect("/login/") teacher_list=sqlheper.get_list("""
select teacher.tid as tid,teacher.name,class.title from teacher
left join teacher_class on teacher_class.teacher_id=teacher.tid
left join class on class.cid=teacher_class.class_id""",[])
# print(teacher_list)
result = {}
for row in teacher_list:
tid = row["tid"]
if tid in result:
result[tid]["titles"].append(row["title"])
else:
result[tid] = {"tid":row["tid"],"name":row["name"],"titles":[row["title"],]} return render(request, "teacher.html", {"teacher_list":result.values()}) #增加
def get_all_class(request):
import time
time.sleep(1)
obj = sqlheper.SqlHelper()
class_list = obj.get_list('select cid,title from class',[])
obj.close()
return HttpResponse(json.dumps(class_list)) def new_teacher(request): ret = {'status': True, 'message': None}
try:
class_list=request.POST.getlist("class_list")
tname=request.POST.get("tname")
teacher_id=sqlheper.get_IncrementId("insert into teacher(name) values(%s)",[tname,]) data_list = []
for cls_id in class_list:
temp = (teacher_id,cls_id,)
data_list.append(temp) obj = sqlheper.SqlHelper()
obj.multiple_modify('insert into teacher_class(teacher_id,class_id) values(%s,%s)', data_list)
obj.close()
except Exception as e:
ret['status'] = False
ret['message'] = str(e)
return HttpResponse(json.dumps(ret)) #编辑
def edit_tea_cls(request): id = request.POST.get("id")
obj = sqlheper.SqlHelper()
class_list = obj.get_list('select cid,title from class',[]) teacher_info = obj.get_one("select tid,name from teacher where tid=%s",[id,]) class_id = obj.get_list("select class_id from teacher_class where teacher_id=%s",[id,]) data_list = []
for cls_id in class_id:
data_list.append(cls_id["class_id"]) print(teacher_info)
total = []
total.append(class_list)
total.append(teacher_info)
total.append(data_list)
obj.close()
return HttpResponse(json.dumps(total)) def modal_edit_teacher(request):
ret = {'status': True, 'message': None}
try:
name = request.POST.get("name")
tid = request.POST.get("tid")
class_ids = request.POST.getlist("class_ids") obj = sqlheper.SqlHelper()
obj.modify("update teacher set name=%s where tid=%s", [name, tid, ])
obj.modify('delete from teacher_class where teacher_id=%s', [tid, ])
data_list = []
for cls_id in class_ids:
temp = (tid, cls_id)
data_list.append(temp)
obj.multiple_modify('insert into teacher_class(teacher_id,class_id) values(%s,%s)', data_list)
obj.close()
except Exception as e:
ret['status'] = False
ret['message'] = str(e)
return HttpResponse(json.dumps(ret))
views.py
Django 相亲小项目
用户登录 如果男用户登录,显示女生列表
如果女用户登录,显示男生列表
from django.shortcuts import render,HttpResponse,redirect
from app01 import models def login(request):
if request.method == "GET":
return render(request,"login.html")
else:
username = request.POST.get("username")
password = request.POST.get("password")
gender = request.POST.get("gender")
if gender == "":
obj = models.Boy.objects.filter(username=username,password=password).first()
else:
obj = models.Girl.objects.filter(username=username,password=password).first()
if not obj:
#未登录
return render(request,"login.html",{"msg":"用户名或密码错误"})
else:
request.session["user_info"] = {"user_id":obj.id,"gender":gender,"username":username,"nickname":obj.nickname}
return redirect("/index.html") def logout(request):
if request.session.get("user_info"):
request.session.clear()
return redirect("/login.html")
views/account.py
from django.shortcuts import render,HttpResponse,redirect
from app01 import models def index(request):
if not request.session.get("user_info"):
return redirect("/login.html")
else:
gender = request.session.get("user_info").get("gender")
if gender == "":
user_list = models.Girl.objects.all()
else:
user_list = models.Boy.objects.all()
return render(request,"index.html",{"user_list":user_list}) def others(request): current_user_id = request.session.get("user_info").get("user_id")
gender = request.session.get("user_info").get("gender")
if gender == "":
user_list = models.B2G.objects.filter(b_id=current_user_id).values("g__nickname")
else:
user_list = models.B2G.objects.filter(g_id=current_user_id).values("b__nickname")
return render(request,"other.html",{"user_list":user_list}) def test(request): # models.Boy.objects.create(nickname="方少伟",username="fsw",password="123")
# models.Boy.objects.create(nickname="陈涛",username="ct",password="123")
# models.Boy.objects.create(nickname="egon",username="egon",password="123")
#
# models.Girl.objects.create(nickname="lili", username="lili", password="123")
# models.Girl.objects.create(nickname="jim", username="jim", password="123")
# models.Girl.objects.create(nickname="xiaojie", username="xiaojie", password="123") # models.B2G.objects.create(b_id=1,g_id=1)
# models.B2G.objects.create(b_id=1,g_id=2)
# models.B2G.objects.create(b_id=1,g_id=3)
# models.B2G.objects.create(b_id=2,g_id=1)
# models.B2G.objects.create(b_id=3,g_id=1)
# models.B2G.objects.create(b_id=4,g_id=1) return HttpResponse("...")
views/love.py
from django.db import models # Create your models here. class Boy(models.Model):
nickname = models.CharField(max_length=32)
username = models.CharField(max_length=32)
password = models.CharField(max_length=64) class Girl(models.Model):
nickname = models.CharField(max_length=32)
username = models.CharField(max_length=32)
password = models.CharField(max_length=64) class B2G(models.Model):
b = models.ForeignKey(to="Boy",to_field="id")
g = models.ForeignKey(to="Girl",to_field="id")
models.py
urlpatterns = [
url(r'^admin/', admin.site.urls), url(r'^test.html$', love.test), url(r'^login.html$', account.login),
url(r'^logout.html$', account.logout), url(r'^index.html$', love.index),
url(r'^others.html$', love.others), ]
urls.py
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body> <form action="/login.html" method="POST">
{% csrf_token %}
<p>用户:<input type="text" name="username"></p>
<p>密码:<input type="password" name="password"></p>
<p>
性别:
男<input type="radio" name="gender" value="">
女<input type="radio" name="gender" value="">
</p> <input type="submit" value="提交">{{ msg }}
</form> </body>
</html>
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body> {% include "user_head.html" %} <h3>异性列表</h3>
<a href="/others.html">查看和我有关系的异性</a>
<ul>
{% for row in user_list %}
<li>{{ row.nickname }}</li>
{% endfor %}
</ul> </body>
</html>
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body> {% include "user_head.html" %} <h3>有关系的异性列表</h3>
<ul>
{% for row in user_list %}
{% if row.g__nickname %}
<li>{{ row.g__nickname }}</li>
{% else %}
<li>{{ row.b__nickname }}</li>
{% endif %}
{% endfor %}
</ul> </body>
</html>
other.html
<h3>当前用户: {{ request.session.user_info.nickname }}</h3>
<a href="/logout.html">注销</a>
user_head.html
Django小项目练习的更多相关文章
- Python之路【第十八篇】Django小项目简单BBS论坛部分内容知识点
开发一个简单的BBS论坛 项目需求: 整体参考“抽屉新热榜” + “虎嗅网” 实现不同论坛版块 帖子列表展示 帖子评论数.点赞数展示 在线用户展示 允许登录用户发贴.评论.点赞 允许上传文件 帖子可被 ...
- Django小项目简单BBS论坛
开发一个简单的BBS论坛 项目需求: 1 整体参考"抽屉新热榜" + "虎嗅网" 2 实现不同论坛版块 3 帖子列表展示 4 帖子评论数.点赞数展示 5 在线用 ...
- Python之路【第十八篇】Django小项目webQQ实现
WEBQQ的实现的几种方式 1.HTTP协议特点 首先这里要知道HTTP协议的特点:短链接.无状态! 在不考虑本地缓存的情况举例来说:咱们在连接博客园的时候,当tcp连接后,我会把我自己的http头发 ...
- Django小项目web聊天
WEBQQ的实现的几种方式 1.HTTP协议特点 首先这里要知道HTTP协议的特点:短链接.无状态! 在不考虑本地缓存的情况举例来说:咱们在连接博客园的时候,当tcp连接后,我会把我自己的http头发 ...
- django小项目,使用paramiko自动备份网络设备配置
原来公司开发团队人员众多,有专门对接运维需求的开发人员,现在想要实现些功能可(只)以(能)自己写了-_- | 周末在家无事,用django搞个简单的功能练练手 django安装,配置 sudo p ...
- Django 小实例S1 简易学生选课管理系统 0 初步介绍与演示
Django 小实例S1 简易学生选课管理系统 第0章--初步介绍与演示 点击查看教程总目录 作者自我介绍:b站小UP主,时常直播编程+红警三,python1对1辅导老师. 1 初步介绍 先介绍下这个 ...
- Django集成celery实战小项目
上一篇已经介绍了celery的基本知识,本篇以一个小项目为例,详细说明django框架如何集成celery进行开发. 本系列文章的开发环境: window 7 + python2.7 + pychar ...
- python3开发进阶-Django框架学习前的小项目(一个简单的学员管理系统)
''' 自己独立写一个学员管理系统 表结构: 班级表: -id -grade_name 学生表: -id -student_name -grade 关联外键班级表 老师表: -id -teacher_ ...
- Django 小实例S1 简易学生选课管理系统 2 新建项目(project)并进行设置
Django 小实例S1 简易学生选课管理系统 第2节--新建项目(project)并进行设置 点击查看教程总目录 作者自我介绍:b站小UP主,时常直播编程+红警三,python1对1辅导老师. 0 ...
随机推荐
- [错误解决]Ubuntu中使用dpkg安装deb文件提示依赖关系问题,仍未被配置
使用dpkg进行软件安装时,提示:dpkg:处理软件包XXX时出错:依赖关系问题,仍未被配置 使用如下命令,sudo apt-get install -f 等分析完之后,重新使用dpkg –i XXX ...
- js原型链继承的傻瓜式详解
本文争取用最简单的语言来讲解原型链继承的OOP原理 0.如果对原型继承还没有大致了解,完全一头雾水,请先阅读 <JavaScript高级程序设计>第六章最后部分的寄生组合式继承 或者_廖雪 ...
- linux下定时任务设置
原文http://www.blogjava.net/freeman1984/archive/2010/09/23/332715.html 觉这篇文章写的挺全的,把它拿过来存在博客里,方便以后查询. 为 ...
- 3D标签
动态实现3D标签, 主要代码: // // XLMatrix.h // XLSphereView // // Created by 史晶晶 on 16/4/4. // Copyright © 2016 ...
- C# 实现图像快速 水平 垂直 翻转
C# 图像水平,垂直翻转的方法,速度很快 重新把图像绘制成翻转的方法 /// <summary> /// 图像水平翻转 /// </summary> /// <para ...
- SpringBoot基础之MockMvc单元测试
SpringBoot创建的Maven项目中,会默认添加spring-boot-starter-test依赖.在<5分钟快速上手SpringBoot>中编写的单元测试使用了MockMvc.本 ...
- 【BZOJ3524】Couriers(主席树)
题意:给一个长度为n的序列a.1≤a[i]≤n.m组询问,每次询问一个区间[l,r],是否存在一个数在[l,r]中出现的次数大于(r-l+1)/2.如果存在,输出这个数,否则输出0. n,m≤5000 ...
- 【NOIP2016练习】T1 挖金矿(二分答案)
题意: 思路:二分答案A 合法的答案 sigma(s[i][xi])/sigma(xi)>=a i<=m sigma(s[i][xi]-a*xi)>=0 对于每个i找到xi使s[i] ...
- luogu 3709 大爷的字符串题 构造 莫队 区间众数
题目链接 题目描述 给你一个字符串a,每次询问一段区间的贡献 贡献定义: 每次从这个区间中随机拿出一个字符\(x\),然后把\(x\)从这个区间中删除,你要维护一个集合S 如果\(S\)为空,你\(r ...
- WebRTC VoiceEngine综合应用示例(二)——音频通话的基本流程(转)
下面将以实现一个音频通话功能为示例详细介绍VoiceEngine的使用,在文末将附上相应源码的下载地址.这里参考的是voiceengine\voe_cmd_test. 第一步是创建VoiceEngin ...