django之form功能
2017-07-07 16:09
344 查看
Django的Form主要具有一下几大功能:
- 生成HTML标签
- 验证用户数据(显示错误信息)
- HTML Form提交保留上次提交数据
- 初始化页面显示内容
1、form的创建:
示例:
class LoginForm(Form): # 正则验证:不能为空,6-18 username=fields.CharField( max_length=18, min_length=6, required=True, error_messages={ 'required':'用户名不能为空', 'min_length':'用户名最少需要6个字符', 'max_length':'用户名最多可用18个字符', }) # 正则验证: 不能为空,16+ password = fields.CharField( min_length=10, required=True, error_messages={ 'required': '密码不能为空', 'min_length': '密码最少需要10个字符', } )
在views.py函数内部的处理:
from django.shortcuts import render,HttpResponse,redirect from django.forms import Form from django.forms import fields class LoginForm(Form): # 正则验证:不能为空,6-18 username=fields.CharField( max_length=18, min_length=6, required=True, error_messages={ 'required':'用户名不能为空', 'min_length':'用户名最少需要6个字符', 'max_length':'用户名最多可用18个字符', }) # 正则验证: 不能为空,16+ password = fields.CharField( min_length=10, required=True, error_messages={ 'required': '密码不能为空', 'min_length': '密码最少需要10个字符', } ) def login(request): if request.method == "GET": return render(request,'login.html') else: obj = LoginForm(request.POST) if obj.is_valid(): # 用户输入格式正确 print(obj.cleaned_data) # 字典类型 return redirect('http://www.cnblogs.com/xuyuanyuan123/') else: # 用户输入格式错误 return render(request,'login.html',{'obj':obj})
url.py
from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^login.html$', views.login), ]
login.html
TextInput(Input) NumberInput(TextInput) EmailInput(TextInput) URLInput(TextInput) PasswordInput(TextInput) HiddenInput(TextInput) Textarea(Widget) DateInput(DateTimeBaseInput) DateTimeInput(DateTimeBaseInput) TimeInput(DateTimeBaseInput) CheckboxInput Select NullBooleanSelect SelectMultiple RadioSelect CheckboxSelectMultiple FileInput ClearableFileInput MultipleHiddenInput SplitDateTimeWidget SplitHiddenDateTimeWidget SelectDateWidgetView Code
常用选择插件
<strong># 单radio,值为字符串</strong> # user = fields.CharField( # initial=2, # widget=widgets.RadioSelect(choices=((1,'上海'),(2,'北京'),)) # ) <strong># 单radio,值为字符串</strong> # user = fields.ChoiceField( # choices=((1, '上海'), (2, '北京'),), # initial=2, # widget=widgets.RadioSelect # ) <strong># 单select,值为字符串</strong> # user = fields.CharField( # initial=2, # widget=widgets.Select(choices=((1,'上海'),(2,'北京'),)) # ) <strong># 单select,值为字符串</strong> # user = fields.ChoiceField( # choices=((1, '上海'), (2, '北京'),), # initial=2, # widget=widgets.Select # ) <strong># 多选select,值为列表</strong> # user = fields.MultipleChoiceField( # choices=((1,'上海'),(2,'北京'),), # initial=[1,], # widget=widgets.SelectMultiple # ) <strong># 单checkbox</strong> # user = fields.CharField( # widget=widgets.CheckboxInput() # ) <strong># 多选checkbox,值为列表</strong> # user = fields.MultipleChoiceField( # initial=[2, ], # choices=((1, '上海'), (2, '北京'),), # widget=widgets.CheckboxSelectMultiple # )
示例:
select的多种写法:
a、单选
# 下拉框的方法1: # cls_id = fields.IntegerField( # widget=widgets.Select(choices=[(1,'上海'),(2,'北京')])) # 下拉框的方法2: # cls_id = fields.CharField( # widget=widgets.Select(choices=[(1,'昌平区'),(2,'海淀区'),(3,'朝阳区')])) # 下拉框的方法3: # cls_id = fields.ChoiceField( # choices=[(1,'10号线'),(2,'8号线'),(3,'5号线')] # )
b、多选
#多选下拉框(有自定义属性) # xdb = fields.MultipleChoiceField( # choices=[(1, '朝阳区'), (2, '海淀区'), (3, '昌平区')], # widget=widgets.SelectMultiple(attrs={'class':'c1'}) #后面参数是定制属性 # ) #单选checkbox # xdb = fields.CharField( # widget=widgets.CheckboxInput() # ) #多选checkbox (多个checkbox,二选一) # xdb = fields.MultipleChoiceField( # initial=[2, ], # choices=((1, '上海'), (2, '北京'),), # widget=widgets.CheckboxSelectMultiple # ) #多个选项Radio (互斥 三选一) # xdb = fields.ChoiceField( # choices=((1, '上海'), (2, '北京'),(3, '北京1'),), # initial=2, # widget=widgets.RadioSelect # )
用form实现验证的功能:(一对一、一对多、多对多)
1、单表的操作:(一对一)====>班级表
首先建立一个新的目录:(该结构如下)
首先先建立表格,在models.py内写入:
from django.db import models class Classes(models.Model): cname=models.CharField(max_length=32) class Student(models.Model): sname=models.CharField(max_length=32) email=models.CharField(max_length=32) age=models.IntegerField(max_length=16) cls=models.ForeignKey('Classes') class Teacher(models.Model): tname=models.CharField(max_length=32) c2t=models.ManyToManyField('Classes') # c2t=models.ManyToManyField('Classes')相当于建立的第四张关系表
urls.py
from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), # =======班级表:单表操作===== url(r'^classes.html$',views.classes), url(r'^add_class.html$',views.add_class), url(r'^edit_class/(\d+)',views.edit_class), url(r'^del_class/(\d+)',views.del_class), # ======班级表和学生表操作:一对多操作===== url(r'^student.html$',views.student), url(r'^add_student.html$',views.add_student), url(r'^edit_student/(\d+)',views.edit_student), url(r'^del_student/(\d+)',views.del_student), # ===========班级表和老师表操作:多对多操作========= url(r'^teacher.html$',views.teacher), url(r'^add_teacher.html$',views.add_teacher), url(r'^edit_teacher/(\d+)',views.edit_teacher), url(r'^del_teacher/(\d+)',views.del_teacher), ]
views.py
from django.shortcuts import render,redirect,HttpResponse from django.forms import Form from app01 import models from django.forms import fields from django.forms import widgets # =========================班级表操作========================= class ClassForm(Form): cname=fields.RegexField('老男孩\d+') def classes(request): cls_list=models.Classes.objects.all() return render(request,"classes.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) print(obj) if obj.is_valid(): # obj.cleaned_data是字典格式 # print(obj.cleaned_data) #如果用户输入的信息无误的话,则需要在数据库中插入用户输入的数据 models.Classes.objects.create(**obj.cleaned_data) return redirect("/classes.html") return render(request,'add_class.html',{'obj':obj}) def edit_class(request,nid): if request.method=="GET": res=models.Classes.objects.filter(id=nid).first() # 让页面显示初始值 # obj = ClassForm(data={'cname': '老男孩3期'})#这里面含有验证规则,有错误信息显示 obj=ClassForm(initial={'cname':res.cname}) return render(request,"edit_class.html",{'nid':nid,'obj':obj}) else: obj=ClassForm(request.POST) if obj.is_valid(): models.Classes.objects.filter(id=nid).update(**obj.cleaned_data) return redirect("/classes.html") return render(request,"edit_class.html",{'nid':nid,'obj':obj}) def del_class(request,nid): models.Classes.objects.filter(id=nid).delete() return redirect("/classes.html")
classes.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>班级列表</h1> <div> <a href="/add_class.html">添加班级</a> </div> <ul> {% for i in cls_list %} <li> {{ i.cname }}|<a href="/edit_class/{{ i.id }}">编辑</a>|<a href="/del_class/{{ i.id }}">删除</a> </li> {% endfor %} </ul> </body> </html>
add_class.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>添加班级</h1> <form method="POST" action="/add_class.html"> {% csrf_token %} <p> {{ obj.cname }}{{ obj.errors.cname.0 }} </p> <p> <input type="submit" value="提交"> </p> </form> </body> </html>
edit_class.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>编辑班级</h1> <form action="/edit_class/{{ nid }}" method="POST"> {% csrf_token %} <p> {{ obj.cname }}{{ obj.errors.cname.0 }} </p> <input type="submit" value="提交"> </form> </body> </html>
页面展示效果图:
2、form验证操作:(一对多)====>班级表和学生表操作:
views.py
from django.shortcuts import render,redirect,HttpResponse from django.forms import Form from app01 import models from django.forms import fields from django.forms import widgets # ================一对多:学生表操作====== class StudentForm(Form): sname=fields.CharField( min_length=2, max_length=6, widget=widgets.TextInput(attrs={'class':'form-control'})#给标签的input框加一个样式 ) email=fields.EmailField( widget=widgets.TextInput(attrs={'class': 'form-control'}) ) age=fields.IntegerField( min_value=18, max_value=30, widget=widgets.TextInput(attrs={'class': 'form-control'}) ) # 下拉框的方法1: # cls_id = fields.IntegerField( # widget=widgets.Select(choices=[(1,'上海'),(2,'北京')])) # 下拉框的方法2: # cls_id = fields.CharField( # widget=widgets.Select(choices=[(1,'昌平区'),(2,'海淀区'),(3,'朝阳区')])) # 下拉框的方法3: # cls_id = fields.ChoiceField( # choices=[(1,'10号线'),(2,'8号线'),(3,'5号线')] # ) cls_id=fields.IntegerField( # widget=widgets.Select(choices=[(1,'上海'),(2,'北京')]) #在这里需要用列表套元祖的方式,所以用values_list widget=widgets.Select(choices=models.Classes.objects.values_list('id', 'cname'),attrs={'class': 'form-control'}) ) def student(request): s_list=models.Student.objects.all() return render(request,"student.html",{"s_list":s_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.html") else: return render(request, "add_student.html", {'obj': obj}) def edit_student(request,nid): if request.method=="GET": ret=models.Student.objects.filter(id=nid).values("sname","email","age","cls_id").first() obj=StudentForm(initial=ret) 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.html") else: return render(request, "edit_student.html", {'nid': nid,'obj':obj}) def del_student(request,nid): models.Student.objects.filter(id=nid).delete() return redirect("/student.html")
student.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>学生列表</h1> <a href="/add_student.html">添加学生</a> <ul> {% for i in s_list %} <li> {{ i.sname }}/{{ i.email }}/{{ i.age }}/{{ i.cls_id }}/{{ i.cls.title }}|<a href="/edit_student/{{ i.id }}">编辑</a>|<a href="/del_student/{{ i.id }}">删除</a> </li> {% endfor %} </ul> </body> </html>
add_student.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>添加学生</h1> <form action="/add_student.html" method="POST"> {% csrf_token %} <p> {{ obj.sname }}{{ obj.errors.sname.0 }} </p> <p> {{ obj.email }}{{ obj.errors.email.0 }} </p> <p> {{ obj.age }}{{ obj.errors.age.0 }} </p> <p> {{ obj.cls_id }}{{ obj.errors.cls_id.0 }} </p> <input type="submit" value="提交" /> </form> </body> </html>
edit_student.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </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.sname }}{{ obj.errors.sname.0 }} </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">邮箱:</label> <div class="col-sm-10"> {{ obj.email }}{{ obj.errors.email.0 }} </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">年龄:</label> <div class="col-sm-10"> {{ obj.age }}{{ obj.errors.age.0 }} </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">班级:</label> <div class="col-sm-10"> {{ obj.cls_id }}{{ obj.errors.cls_id.0 }} </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>
页面效果图展现:
3、form表单验证:班级表和老师表(多对多的关系)
views.py
from django.shortcuts import render,redirect,HttpResponse from django.forms import Form from app01 import models from django.forms import fields from django.forms import widgets # ============多对多:老师表操作=============== class TeacherForm(Form): tname=fields.CharField(min_length=2) cls_name=fields.MultipleChoiceField( choices=models.Classes.objects.values_list("id","cname"), widget=widgets.SelectMultiple ) def teacher(request): t_list=models.Teacher.objects.all() return render(request,"teacher.html",{'t_list':t_list}) def add_teacher(request): if request.method=="GET": obj=TeacherForm() return render(request,"add_teacher.html",{'obj':obj}) else: obj=TeacherForm(request.POST) if obj.is_valid(): print(obj.cleaned_data) cls_name=obj.cleaned_data.pop("cls_name") row=models.Teacher.objects.create(**obj.cleaned_data) # print(cls_name) print(row) row.c2t.add(*cls_name) return redirect('/teacher.html') return render(request, "add_teacher.html", {'obj': obj}) def edit_teacher(request,nid): if request.method=="GET": res=models.Teacher.objects.filter(id=nid).first()#取到老师的id和老师的姓名 #需要取到班级的id class_id=res.c2t.values_list("id") # print(class_id)#是一个字符串 # cid_list=[] cid_list=list(zip(*class_id))[0] if list(zip(*class_id)) else [] # 使用三元表达式cid_list=list(zip(*class_id))[0] if list(zip(*class_id)) else [] obj=TeacherForm(initial={'tname':res.tname,'cid_list':cid_list}) return render(request,"edit_teacher.html",{'nid':nid,'obj':obj}) else: obj=TeacherForm(request.POST) if obj.is_valid(): # print(obj.cleaned_data)#{'tname': 'alex', 'cls_name': ['1', '2']} cls_name=obj.cleaned_data.pop("cls_name") print(cls_name) ret=models.Teacher.objects.filter(id=nid).update(**obj.cleaned_data) res=models.Teacher.objects.filter(id=nid).first() # print(ret) print(res) # res.c2t.remove() res.c2t.set(cls_name) return redirect("/teacher.html") else: print("ok") return render(request, "edit_teacher.html", {'nid': nid, 'obj': obj}) def del_teacher(request,nid): models.Teacher.objects.filter(id=nid).delete() return redirect("/teacher.html")
teacher.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>老师列表</h1> <a href="/add_teacher.html">添加老师</a> <table border="1px"> <thead> <tr> <th>老师ID</th> <th>老师姓名</th> <th>任教班级</th> <th>操作</th> </tr> </thead> <tbody> {% for i in t_list %} <tr> <th>{{ i.id }}</th> <th>{{ i.tname }}</th> <th> {% for j in i.c2t.all %} {{ j.cname }} {% endfor %} </th> <th> <a href="/edit_teacher/{{ i.id }}">编辑</a> | <a href="/del_teacher/{{ i.id }}">删除</a> </th> </tr> {% endfor %} </tbody> </table> </body> </html>
add_teacher.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>添加老师</h1> <form action="/add_teacher.html" method="POST"> {% csrf_token %} <p> 老师姓名:{{ obj.tname }}{{ obj.errors.tname.0 }} </p> <p> 老师班级:{{ obj.cls_name }}{{ obj.errors.cls_name.0 }} </p> <input type="submit" value="提交"> </form> </body> </html>
edit_teacher.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>编辑老师</h1> <form method="POST" action="/edit_teacher/{{ nid }}"> {% csrf_token %} <p> {{ obj.tname }}{{ obj.errors.tname.0 }} </p> <p> {{ obj.cls_name }}{{ obj.errors.cls_name.0 }} </p> <input type="submit" value="提交"> </form> </body> </html>
页面展现效果图:
相关文章推荐
- Django之强大的Form功能
- Django之强大的Form功能
- Django-全局搜索功能
- django form 验证end_time不小于start_time
- 利用 FormData 对象和 Spring MVC 配合实现Ajax文件下载功能
- Django 之 ModelForm 组件
- 用xmlhttp将html的数据打包成multipart/form-data格式,实现异步上传文件功能
- Django模拟新浪微博的@功能
- 循序渐进Python3(十三) --0-- django之form表单
- Django 实现增删改查、登录功能
- Django的form表单之文件上传
- django_Form_自定义钩子
- C# Form窗体的功能操作,无边框窗体的移动,无边框窗体的尺寸缩放,保存和恢复窗体的尺寸和坐标信息
- Django Form 详解
- WSS 3.0与Form Server 2007、MOSS 2007各版本功能对比(6)
- Python之路【第二十一篇】:Django之Form组件
- 教你用Django实现一个简单的GIS功能
- Django中扩展TinyMCE使其支持图片上传功能
- django form tips
- Django 框架之Form组件