Django (四)用Form组件进行数据验证
程序员文章站
2022-04-25 15:21:26
...
一、作业内容
1、班级表的操作,包括增加、编辑、删除。要求:(1)数据库操作用ORM;(2)用Form组件进行数据验证,通过Ajax发请求。
2、学生表的操作,包括增加、编辑、删除。要求:数据库操作用ORM。
3、教师表的操作,包括增加、编辑、删除。要求:数据库操作用ORM。
班级表
classes代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>添加班级</title>
</head>
<body>
<h3>添加班级</h3>
<form id="f1" method="post" action="{% url "classes:class_add" %}">
<p><input type="text" name="title" placeholder="班级名称"></p>
<p><input type="button" id="btnAdd" value="添加"></p>
</form>
<script src="/static/jquery-3.4.1.min.js"></script>
<script>
$(function(){
$("#btnAdd").click(function(){
$(".error").remove();
$.ajax({
url:"{% url "classes:class_add" %}",
type:"post",
data:$("#f1").serialize(),
success:function(args){
args=JSON.parse(args);
if(args.status){
location.herf="{% url "classes:classes" %}";
}
else{
$.each(args.errmsg,function(index,value){
var tag=document.createElement("span");
tag.innerText=value[0];
tag.className="error"
$("#f1").find('input[name="'+index+'"]').after(tag)
})
}
}
})
});
})
</script>
</body>
</html>
from django.shortcuts import render, HttpResponse, redirect
from django.views.generic import View
from apps.utils.sqlhelp import SqlHelper
from apps.classes.models import ClassDB
from django.forms import Form,fields,widgets
import json
class ClassForm(Form):
title=fields.CharField(
required=True,
min_length=2,
max_length=20,
error_messages={
"required":"班级名称不能为空!",
"min_length":"太短了!",
"max_length":"太长了!",
}
)
class ClassesView(View):
def get(self,request):
result=ClassDB.objects.all()
return render(request, "class.html", {"result":result})
class Class_addf(View):
def get(self,request):
return render(request, "addclass.html")
def post(self,request):
ret={"status":True,"errmsg":None}
obj=ClassForm(request.POST)
if obj.is_valid():
ClassDB.objects.create(**obj.cleaned_data)
# title = request.POST.get("title")
# ClassDB.objects.create(title=title)
else:
ret["status"]=False
ret["errmsg"]=obj.errors
return HttpResponse(json.dumps(ret))
# return redirect("classes:classes")
class Class_delf(View):
def get(self,request):
cid=request.GET.get("cid")
ClassDB.objects.filter(id=cid).delete()
return redirect("classes:classes")
class Class_updataf(View):
def get(self,request):
cid=request.GET.get("cid")
title = request.GET.get("title")
return render(request, "edit.html", {"cid":cid, "title":title})
def post(self,request):
ret = {"status": True, "errmsg": None}
obj = ClassForm(request.POST)
if obj.is_valid():
# cid = request.POST.get("cid")
# title = request.POST.get("title")
# result = ClassDB.objects.filter(id=cid).update(title=title)
cid = request.POST.get("cid")
ClassDB.objects.filter(id=cid).update(**obj.cleaned_data)
else:
ret["status"] = False
ret["errmsg"] = obj.errors
return HttpResponse(json.dumps(ret))
学生表
students代码:
from django.shortcuts import render, HttpResponse, redirect
from django.views.generic import View
from apps.utils.sqlhelp import SqlHelper
from apps.students.models import Student
from apps.classes.models import ClassDB
from django.db.models import F
from django.forms import Form,fields,widgets
import json
class StudentForm(Form):
name=fields.CharField(
required=True,
min_length=2,
max_length=20,
error_messages={
"required":"学生姓名不能为空!",
"min_length":"太短了!",
"max_length":"太长了!",
}
)
sc_id =fields.IntegerField(
required=True,
error_messages={
"required":"要选一个班级!",
}
)
class Students(View):
def get(self,request):
result = Student.objects.all().values("id", "name").annotate(title=F("sc__title"))
return render(request, "student_class.html", {"result": result})
class Student_addf(View):
def get(self,request):
result=ClassDB.objects.all()
return render(request,"student_add.html",{"result":result})
def post(self,request):
ret = {"status": True, "errmsg": None}
obj = StudentForm(request.POST)
if obj.is_valid():
# student_name = request.POST.get("student_name")
# cid = request.POST.get("student_class")
# Student.objects.create(name=student_name, sc_id=cid)
Student.objects.create(**obj.cleaned_data)
else:
ret["status"] = False
ret["errmsg"] = obj.errors
return HttpResponse(json.dumps(ret))
# return redirect("students:students")
class Student_delf(View):
def get(self,request):
student_id=request.GET.get("student_id")
Student.objects.filter(id=student_id).delete()
return redirect("students:students")
class Student_updataf(View):
def get(self,request):
student_id=request.GET.get("student_id")
student_name = request.GET.get("student_name")
result=ClassDB.objects.all()
cid=Student.objects.filter(id=student_id).first()
return render(request,"student_edit.html",{"student_id":student_id,"student_name":student_name,"result":result,"class_id":cid})
def post(self,request):
ret = {"status": True, "errmsg": None}
obj = StudentForm(request.POST)
if obj.is_valid():
sid = request.POST.get("sid")
name=obj.cleaned_data["name"]
cid=obj.cleaned_data["sc_id"]
Student.objects.filter(id=sid).update(name=name, sc_id=cid)
else:
ret["status"] = False
ret["errmsg"] = obj.errors
return HttpResponse(json.dumps(ret))
# return redirect("students:students")
教师表
teachers代码:
from django.shortcuts import render,HttpResponse,redirect
from apps.utils.sqlhelp import SqlHelper
from django.views.generic import View
from apps.classes.models import ClassDB
from apps.teachers.models import Teacher
from django.db.models import F
# Create your views here.
from django.forms import Form,fields,widgets
import json
class TeacherForm(Form):
name=fields.CharField(
required=True,
min_length=2,
max_length=20,
error_messages={
"required":"学生姓名不能为空!",
"min_length":"太短了!",
"max_length":"太长了!",
}
)
tc_ids =fields.MultipleChoiceField(
required=True,
error_messages={
"required":"要选一个班级!",
}
)
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
self.fields["tc_ids"].choices=ClassDB.objects.values_list("id","title")
class Teachers(View):
def get(self,request):
result = Teacher.objects.all().values("id", "name") \
.annotate(title=F("tc__title"))
dic={}
for item in result:
if item["id"] in dic:
dic[item["id"]]["titles"].append(item["title"])
else:
dic[item["id"]]={"id":item["id"],"name":item["name"],"titles":[item["title"]]}
result=dic.values()
return render(request,"teachers.html",{"result":result})
class Teacher_addf(View):
def get(self,request):
result=ClassDB.objects.all()
return render(request,"teacher_add.html",{"result":result})
def post(self,request):
ret = {"status": True, "errmsg": None}
obj = TeacherForm(request.POST)
if obj.is_valid():
teacher_name = request.POST.get("name")
teacher_class = request.POST.getlist("tc_ids")
row = Teacher.objects.create(name=teacher_name)
row.tc.add(*teacher_class)
# Teacher.objects.create(**obj.cleaned_data)
else:
ret["status"] = False
ret["errmsg"] = obj.errors
return HttpResponse(json.dumps(ret))
# return redirect("teachers:teachers")
class Teacher_delf(View):
def get(self,request):
tid=request.GET.get("teacher_id")
info=Teacher.objects.filter(id=tid).first()
info.tc.remove(tid)
Teacher.objects.filter(id=tid).delete()
return redirect("teachers:teachers")
class Teacher_updataf(View):
def get(self,request):
teacher_id=request.GET.get("teacher_id")
teacher_name = request.GET.get("teacher_name")
tinfo=Teacher.objects.filter(id=teacher_id)
result=ClassDB.objects.all()
tmp=Teacher.objects.filter(id=teacher_id).values("id","tc")
lst=[item["tc"] for item in tmp]
return render(request,"teacher_edit.html",{"teacher_id":teacher_id,"teacher_name":teacher_name,"result":result,"teacher_cids":lst})
def post(self,request):
ret = {"status": True, "errmsg": None}
obj = TeacherForm(request.POST)
if obj.is_valid():
teacher_id = request.POST.get("teacher_id")
teacher_name = request.POST.get("teacher_name")
teacher_classes = request.POST.getlist("tc_ids")
tinfo = Teacher.objects.filter(id=teacher_id).first()
tmp = Teacher.objects.filter(id=teacher_id).values("id", "tc")
lst = [item["tc"] for item in tmp]
print(lst)
tinfo.tc.remove(*lst)
tinfo.tc.add(*teacher_classes)
Teacher.objects.filter(id=teacher_id).update(name=teacher_name)
else:
ret["status"] = False
ret["errmsg"] = obj.errors
return HttpResponse(json.dumps(ret))
上一篇: [转]八大排序算法