Django Form组件 学生管理系统
from django.db import models # Create your models here. class Classes(models.Model): title=models.CharField(max_length=32) class Student(models.Model): name=models.CharField(max_length=32) email=models.CharField(max_length=32) age=models.IntegerField(max_length=32) cls=models.ForeignKey("Classes") class Teacher(models.Model): tname=models.CharField(max_length=32) c2t=models.ManyToManyField('Classes')
"""s4day77 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^login/', views.login), url(r'^ajax_login/', views.ajax_login), url(r'^class_list/', views.class_list), url(r'^add_class/', views.add_class), url(r'^edit_class/(\d+)/', views.edit_class), url(r'^del_class/(\d+)/',views.del_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'^del_student/(\d+)/',views.del_student), url(r'^teacher_list/',views.teacher_list), url(r'^add_teacher/',views.add_teacher), url(r'^edit_teacher/(\d+)/',views.edit_teacher),
from django.shortcuts import render,HttpResponse,redirect # Create your views here. from app01 import models from django.forms import Form from django.forms import fields #字段包含正则表达式 from django.forms import widgets #导入插件 class ClassesForm(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=ClassesForm() #实例出一个对象,此时的obj为空值,为创建input标签 return render(request,'add_class.html',{'obj':obj}) else: obj=ClassesForm(request.POST) if obj.is_valid(): #校验值 # 需要往数据库增加数据 # print(obj.cleaned_data) #打印前端传来的字典格式数据 models.Classes.objects.create(**obj.cleaned_data)#因为数据是字典类型 增加的时候也可以是字典格式,索引直接**加数值 return redirect('/class_list/') else: print(obj.errors) 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=ClassesForm(initial={'title':row.title}) #初始默认值 return render(request,'edit_class.html',{'nid':nid,'obj':obj}) #创建空input标签 else: obj=ClassesForm(request.POST) if obj.is_valid(): models.Classes.objects.filter(id=nid).update(**obj.cleaned_data) return redirect('/class_list/') else: print(obj.errors) return render(request,'edit_class.html',{'nid':nid,'obj':obj}) def del_class(request,nid): if request.method == "GET": models.Classes.objects.filter(id=nid).delete() return redirect('/class_list/') class StudentForm(Form): name=fields.CharField( min_length=2, max_length=6, ) email=fields.EmailField() age=fields.IntegerField(min_value=18,max_value=25) cls_id=fields.IntegerField(widget=widgets.Select(choices=models.Classes.objects.values_list("id","title")))#选择下拉框 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/') else: print(obj.errors) return render(request,'add_student.html',{'obj':obj}) def edit_student(request,nid): if request.method == "GET": #从学生数据库拿取name,email,age,cls_id值 row=models.Student.objects.filter(id=nid).values("name","email","age","cls_id").first() obj=StudentForm(initial=row) #添加为默认值 name,email,age,cls_id return render(request,'edit_student.html',{"nid":nid,"obj":obj}) #把obj放进前端 生成input标签 else: obj=StudentForm(request.POST) #前端传来的值以post方式取值 if obj.is_valid(): #进行校验 models.Student.objects.filter(id=nid).update(**obj.cleaned_data) #正确校验的值,在进行更新 return redirect('/student_list/') else: print(obj.errors) return render(request,'edit_student.html',{"nid":nid,"obj":obj}) def del_student(request,nid): if request.method =="GET": #GET方式取nid models.Student.objects.filter(id=nid).delete() return redirect('/student_list/') class TeacherFrom(Form): tname=fields.CharField(min_length=2) xx=fields.MultipleChoiceField( #多选框用MultipleChoiceField # choices=models.Classes.objects.values_list("id","title"), widget=widgets.SelectMultiple) #多选框 def __init__(self,*args,**kwargs): #修复一个小bug,定义一个init方法,继承TeacherTrom的内容, #构造自己都有的方法,每次实例化出来的对象。 super(TeacherFrom,self).__init__(*args,**kwargs) self.fields['xx'].widget.choices=models.Classes.objects.values_list("id","title") def teacher_list(request): tea_list=models.Teacher.objects.all() #获取到老师所有的信息列表 return render(request,'teacher_list.html',{'tea_list':tea_list}) #将老师列表的信息传入到HTML def add_teacher(request): if request.method == "GET": #如果是get方式,让用户看见add_teacher.html页面 obj=TeacherFrom() #实例化一个空对象 return render(request,'add_teacher.html',{"obj":obj})#将实例化的对象传入前端页面进行设置input框 else: obj=TeacherFrom(request.POST) #后台取值操作 post方式 if obj.is_valid(): #对form提交 的值进行校验, xx=obj.cleaned_data.pop("xx") #从字典里面的数据移除xx row=models.Teacher.objects.create(**obj.cleaned_data)#向老师列表中添加一条信息 row.c2t.add(*xx)#向关联第三张表中添加数据 return redirect("/teacher_list/") else: print(obj.errors) return render(request, 'add_teacher.html', {"obj": obj}) def edit_teacher(request,nid): if request.method == "GET": row=models.Teacher.objects.filter(id=nid).first() class_ids=row.c2t.values_list('id') # print(class_ids) # print(".......") #class_ids=[] 如果是这个方式的话 就可以用循环来做 然后添加到class_ids[]中 id_list=list(zip(*class_ids))[0]if list(zip(*class_ids)) else[] #是一个列表的值 obj=TeacherFrom(initial={'tname':row.tname,'xx':id_list}) #设置默认值initial={}字典格式 return render(request,'edit_teacher.html',{'nid':nid,'obj':obj}) else: obj=TeacherFrom(request.POST) if obj.is_valid(): # print(obj.cleaned_data) #取到数据 xx = obj.cleaned_data.pop('xx') #将xx移除到clas_id row=models.Teacher.objects.filter(id=nid) #查看教师的对应的id值 row.update(**obj.cleaned_data) #更新老师数据库里面的内容 row.first().c2t.set(xx) # return redirect("/teacher_list/") else: print(obj.errors) return render(request,'edit_teacher.html',{'nid':nid,'obj':obj})
class_list: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h3>班级信息</h3> <div> <a href="/add_class">添加</a> </div> <form method="POST" action="/class_list"> {% csrf_token %} <ul> {% for row in cls_list %} <li> {{ row.title }} <a href="/edit_class/{{ row.id }}/">编辑</a> | <a href="/del_class/{{ row.id }}/">删除</a> </li> {% endfor %} </ul> </form> </body> </html> add_class: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h3>添加班级</h3> <form method="POST" action="/add_class/"> {% csrf_token %} {{ obj.title }}{{ obj.errors.title.0 }} <p> <input type="submit" value="提交"> </p> </form> </body>
edit_class : <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h3>编辑班级信息</h3> <form method="POST" action="/edit_class/{{ nid }}/"> {% csrf_token %} <p> {{ obj.title }}{{ obj.errors.title.0 }} </p> <p> <input type="submit" value="提交"/> </p> </form> </body> </html>
student_list: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h3>班级信息</h3> <div> <a href="/add_student/">添加</a> </div> <ul> {% for row in stu_list %} <li> {{ row.id }} {{ row.name}} {{ row.email}} {{ row.cls_id }} {{ row.cls_title }} | <a href="/edit_student/{{ row.id }}/">编辑</a> | <a href="/del_student/{{ row.id }}/">删除</a> </li> {% endfor %} </ul> </body> </html> add_student: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h3>添加学生信息</h3> <form method="POST" action="/add_student/"> {% csrf_token %} <p>用户名 {{ obj.name }} {{ obj.errors.name.0 }} </p> <p>邮箱 {{ obj.email }}{{ obj.errors.name.0 }} </p> <p>年龄 {{ obj.age}}{{ obj.errors.age.0 }} </p> <p>班级名称 {{ obj.cls_id }}{{ obj.errors.cls_id.0 }} </p> <p> <input type="submit" value="提交"> </p> </form> </body> </html>
edit_student: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="/static/plugins/bootstrap-3.3.7-dist/css/bootstrap.css"> </head> <body> <h1>编辑学生信息</h1> <div style="width: 500px;margin: 0 auto"></div> <form class="form-horizontal" method="POST" action="/edit_student/{{ nid }}/"> {% csrf_token %} <p>用户名 {{ obj.name }} {{ obj.errors.name.0 }} </p> <p>邮箱 {{ obj.email }}{{ obj.errors.name.0 }} </p> <p>年龄 {{ obj.age}}{{ obj.errors.age.0 }} </p> <p>班级名称 {{ obj.cls_id }}{{ obj.errors.cls_id.0 }} </p> <p> <input type="submit" value="提交"> </p> {#<div class="form-group">#} {# <label class="col-sm-2 control-label">姓名:</label>#} </div> </form> </body> </html>
teacher_list : <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h3>老师列表</h3> <div> <a href="/add_teacher/">添加</a> </div> <table> <tr> <th>ID</th> <th>老师姓名</th> <th>任教班级</th> </tr> {% for row in tea_list %} <tr> <td>{{ row.id }}</td> <td>{{ row.tname}}</td> {# <td>{{ row.c2t.all}}</td>#} <td> {% for i in row.c2t.all %} {{ i.title }} {% endfor %} </td> <td> <a href="/edit_teacher/{{ row.id }}/">编辑</a> </td> </tr> {% endfor %} </table> </body> </html> add_teacher: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h3>添加老师列表</h3> <form method="POST" action="/add_teacher/"> {% csrf_token %} <p>老师姓名: {{ obj.tname }} </p> <p> 任教班级: {{ obj.xx }} </p> <p> <input type="submit" value="提交"> </p> </form> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h3>编辑老师信息</h3> <form method="POST" action="/edit_teacher/{{ nid }}/"> {% csrf_token %} <p>老师姓名: {{ obj.tname }} </p> <p> 任教班级: {{ obj.xx }} </p> <p> <input type="submit" value="提交"> </p> </form> </body> </html>