1.可能用到的模块:
1 from django.shortcuts import render,redirect,HttpResponse 2 from django.forms import Form #Form模块 3 from django.forms import fields 4 from django.forms import widgets 5 from app01 import models 6 from django.core.exceptions import ValidationError #自定义验证规则,抛出异常
2.Form类的创建:
1 class StudentInfo(Form): 2 sname = fields.CharField(max_length=6,min_length=2) 3 email = fields.EmailField(min_length=3) 4 age = fields.IntegerField(min_value=0,max_value=100) #数字限制只有大小没有长度 5 cls_id = fields.IntegerField(widget=widgets.Select) 6 #widget部件可以自定制from插件,如select,radio等 7 8 #当字段限制来自一个表,需要对__init__方法里的self.fields对应的字段值在每次实例化时重新查询值,保持数据的同步,即表内容增加,这里的限制内容也增加。 9 def __init__(self,*args,**kwargs): 10 super(StudentInfo,self).__init__(*args,**kwargs)
#注意:如上面的cls_id 为 fields.MultipleChoiceField(widget=widgets.SelectMultiple),诸如此类多选,则self.felds[].widget
需要去掉,直接为self.felds[].choices.....
11 self.fields['cls_id'].widget.choices = models.Classes.objects.values_list('id','title')
3.应用:
1 #Django 后端: 2 3 def add_student(request): 4 if request.method == 'GET': 5 obj = StudentInfo() #实例化类,获得类的全部字段并传到前端 6 return render(request, 'add_student.html',{'obj':obj}) 7 8 else: 9 obj = StudentInfo(request.POST) #将post拿到的数据传入类中验证 10 if obj.is_valid(): 11 #如果根据规则验证成功,拿到的数据如果字段名与数据表完全一致可以直接添加 12 models.Student.objects.create(**obj.cleaned_data) 13 return redirect('/student.html') 14 #验证失败,数据再返回,根据obj.errors.字段名可以拿到错误信息,此时用户填写的数据还会显示在页面上。 15 return render(request,'add_student.html',{'obj':obj}) 16 17 #models: 18 from django.db import models 19 20 # Create your models here. 21 class Classes(models.Model): 22 title = models.CharField(max_length=16) 23 24 class Student(models.Model): 25 sname = models.CharField(max_length=32) 26 email = models.EmailField(max_length=32) 27 age = models.IntegerField() 28 cls = models.ForeignKey('Classes') 29 30 class Teacher(models.Model): 31 tname = models.CharField(max_length=32) 32 t2c = models.ManyToManyField('Classes') 33 34 35 #前端: 36 <!DOCTYPE html> 37 <html lang="en"> 38 <head> 39 <meta charset="UTF-8"> 40 <title>Title</title> 41 </head> 42 <body> 43 <form action="/add_teacher.html" method="POST" novalidate> 44 {% csrf_token %} 45 <p>姓名:{{ obj.tname }}{{ obj.errors.tname.0 }}</p> 46 <p>任教班级:{{ obj.t2c}}{{ obj.errors.t2c.0 }}</p> 47 <input type="submit" value="提交"> 48 </form> 49 </body> 50 </html> 51 52 form简单应用
4.自定制验证规则:
1 - is_valid 2 - 字段 = 默认正则表达式 3 - 额外的正则 4 from django.forms import Form 5 from django.forms import widgets 6 from django.forms import fields 7 from django.core.validators import RegexValidator 8 9 class MyForm(Form): 10 user = fields.CharField( 11 validators=[RegexValidator(r'^[0-9]+$', '请输入数字'), RegexValidator(r'^159[0-9]+$', '数字必须以159开头')], 12 ) 13 14 15 - clean_字段,必须返回值 16 def clean_user(self): 17 v = self.cleaned_data['user'] 18 if models.UserInfo.objects.filter(user=v).count(): 19 #判断获取到的user在数据库已经存在,主动抛出异常,内部捕获到异常则将异常添加到obj.errors里。 20 raise ValidationError('用户名已经存在') 21 return self.cleaned_data['user'] 22 23 - clean() 24 有返回值:cleaned_data = 返回值 25 无返回值:cleaned_data = 原来的值
5.文件上传:
实现form表单获取用户上传的文件
1 #Django常规方法处理文件上传 2 def f1(request): 3 if request.method == "GET": 4 return render(request,'f1.html') 5 else: 6 import os 7 # request.POST 8 file_obj = request.FILES.get('fafafa') #取文件时,需以FILES获取文件数据 9 f = open(os.path.join('static',file_obj.name),'wb') #写字节方式打开空文件,拼接文件路径 10 for chunk in file_obj.chunks(): #Django文件处理有.chuanks()方法,一块一块的读数据 11 f.write(chunk) #同时写入本地空文件 12 f.close() #写入完成关闭文件 13 return render(request,'f1.html') 14 15 #定制Form方法处理文件上传 16 class F2Form(Form): 17 user = fields.CharField() 18 fafafa = fields.FileField() #对应的字段FileField() 19 20 def f2(request): 21 if request.method == "GET": 22 obj = F2Form() 23 return render(request,'f2.html',{'obj':obj}) 24 else: 25 # 获取form表单提交的数据,文本数据用POST获取,文件用FILES 26 obj = F2Form(data=request.POST,files=request.FILES) 27 if obj.is_valid(): 28 print(obj.cleaned_data.get('fafafa').name) #.name 文件名 29 print(obj.cleaned_data.get('fafafa').size) #.size 文件大小 30 return render(request,'f2.html',{'obj':obj})
1 #f1.html: 2 <!DOCTYPE html> 3 <html lang="en"> 4 <head> 5 <meta charset="UTF-8"> 6 <title></title> 7 </head> 8 <body> 9 #当form中有文件需要接收时,需添加属性 enctype="multipart/form-data" 10 <form method="POST" action="/f1/" enctype="multipart/form-data"> 11 {% csrf_token %} 12 <input type="text" name="user" /> 13 <input type="file" name="fafafa" /> 14 <input type="submit" value="提交" /> 15 </form> 16 </body> 17 </html> 18 19 #f2.html 20 <!DOCTYPE html> 21 <html lang="en"> 22 <head> 23 <meta charset="UTF-8"> 24 <title></title> 25 </head> 26 <body> 27 <form method="POST" action="/f2/" enctype="multipart/form-data"> 28 {% csrf_token %} 29 30 {{ obj.user }} 31 {{ obj.fafafa }} 32 33 <input type="submit" value="提交" /> 34 </form> 35 </body> 36 </html>