一、新建1个 forms.py 模块,并导入 django.forms 模块html
二、在 forms.py 模块中定义1个 form 类,和 moldes 类 类似python
三、在 views.py 导入forms.py模块, 并实例化1个 form 表单对象,并返回这个实例对象数据库
四、在templates文件夹中 定义好form.html 模版django
注意:json
#forms.pyapp
from django import forms #导入Django.forms 模块 from django.http import HttpRequest class Alongin(forms.Form): username=forms.CharField(max_length=30) email=forms.EmailField(required=True) #required 是否惟一 ip=forms.GenericIPAddressField()
#view.pyui
from django.shortcuts import render from app01.forms import Alongin #从forms.py模块中 导入,Alongin类 def form(request): obj=Alongin() #实例化这个表单对象 return render(request,'form.html',{'data':obj}) #在form.html 中返回这个obj对象
#form.htmlspa
<body> <form action=' ' method='POST'> <div> {{data.username}}</div> <div> {{data.email}}</div> <div> {{data.ip}} </div> </form> </body>
外键:forms.ModelChoiceField(queryset=models.UserGroup.objects.all()).net
多对多:forms.ModelMultipleChoiceField(queryset=models.Organizations.objects.all())code
让外键字段数据随着model 更新而更新
def __init__(self, *args, **kwargs): super(UserInfoForm,self).__init__(*args, **kwargs) self.fields['user_type'].choices = models.UserType.objects.values_list('id','caption')
一、is_valid 验证表单提交的内容是否合法
注意中间只有1个下划线 ,根据是否合法,返回True 或 Faluse
#修改views.py
def form(request): obj=Alongin() #建立表单类 if request.method=='POST': CheckForm=Alongin(request.POST) #获取实例对象中传人的表单内容,通常是1个字典组成的对象 CheckResust=CheckForm.is_valid() #验证表单 print(CheckForm,CheckResust ,sep="\n") #以换行的方式打印 return render(request,'form.html',{'data':obj}) #在html 中生成表单
二、实例化的from 类展示形式
from contact.forms import ContactForm f = ContactForm() print(f) #输出 默认以html格式输出 <tr><th><label for="id_subject">Subject:</label></th><td><input type="text" name="subject" id="id_subject" /></td></tr> <tr><th><label for="id_email">Email:</label></th><td><input type="text" name="email" id="id_email" /></td></tr> <tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_mmessage /></td></tr>
as_ul(): 列表形式返回
as_p() : 段落形式返回
>>> print f.as_ul() <li><label for="id_subject">Subject:</label> <input type="text" name="subject" id="id_subject" /></li> <li><label for="id_email">Email:</label> <input type="text" name="email" id="id_email" /></li> <li><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></li> >>> print f.as_p() <p><label for="id_subject">Subject:</label> <input type="text" name="subject" id="id_subject" /></p> <p><label for="id_email">Email:</label> <input type="text" name="email" id="id_email" /></p> <p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></p>
能够用 is_bound 检测
f = ContactForm({'subject': 'Hello', 'email': 'adrian@example.com', 'message': 'Nice site!'}) f.is_bound 》True #输出
输出request.POST提交信息, 返回1个字典 <class 'dict'>
提交后在数据库中保存
models.xxx.object.create(**obj.cleaned_data)
f.cleaned_data {message': uNice site!, email: uadrian@example.com, subject: uHello}
def form(request): obj=Alongin() if request.method=='POST': CheckForm=Alongin(request.POST) print(CheckForm.errors) #输出错误内容 print(type(CheckForm.errors)) #输出错误类型 '''输出内容 一、CheckForm.errors: <ul class="errorlist"> <li>ip <ul class="errorlist"> <li>Enter a valid IPv4 orIPv6 address.</li> </ul> </li> </ul> 二、type(CheckForm.errors): <class 'django.forms.utils.ErrorDict'> '''
注意:一、当CheckForm.errors 的错误信息为多个时,程序默认以as_ul() 的方式输出
二、经过type(CheckForm.errors) ,可发现它是1个django.forms.utils.ErrorDict 对象
三、能够经过 ErrorDict 这个对象,在前台模版人为的返回错误信息
ErrorDict 在django 1.10 中有5个属性,as_ul() ,as_json(),as_data(),as_text() ,__str__
特别说明: __str__ 默认返回 as_ul()
#后台views.py 代码
#能够经过 ErrorDict 这个对象,在前台模版人为的返回错误信息 def form(request): obj=Alongin() #定义1个对象 status={} #由于考虑请求具体为POST 和GET 因此定义1个全局变量,用于返回错误 if request.method=='POST': CheckForm=Alongin(request.POST) CheckResust=CheckForm.is_valid() print(CheckForm,CheckResust ,sep="\n") #输出 request.POST 提交信息,是否有错 print(CheckForm.as_p()) #输出 request.POST 提交信息 以段落方式展现 ,注意as_p() 加括号 print(CheckForm.as_ul()) #输出 request.POST 提交信息 以列表方式展现 ,注意as_ul() 加括号 print(CheckForm.cleaned_data) #输出格式化后的 request.POST信息 print(CheckForm.errors) #输出错误内容 print(type(CheckForm.errors)) #输出错误类型 #定义这个错误对象 CheckForm.errors >> utils.ErrorDict if CheckResust: # 为真 即 is_valid ==True return render(request,'form.html',{'data':obj}) else: status=CheckForm.errors return render(request,'form.html',{'data':obj,'status':status})
#前台模版 form.html
<form method='POST'> <div>用户名: {{data.username}}</div> <div>邮箱: {{data.email}}</div> <div>IP:{{data.ip}} </div> <input type='submit' value='提交'></input> <div style='color:red'> {{status.as_ul}} </div> #注意这里的as_ul 为属性 不加() </form>
七、自定义错误信息
可在定义form 类的时候,添加自定义错误信息
error_messages :错误内容
required:必须的,不能为空
invalid: 格式错误
max_length: 最大长度
min_length:最小长度
from django import forms class FM(forms.Form): username = forms.CharField( max_length=12, min_length=6, error_messages={'required':'用户名不能为空', 'max_length':'请输入最小长度为6位数的用户名', 'max_length':'用户名最大长度不能超过12位' } ) pwd = forms.CharField( max_length=12, min_length=6, error_messages={'required':'密码不能为空'} ) email =forms.EmailField( error_messages={'required':'邮箱不能为空','invalid':'邮箱格式错误'} )
其余错误内容,查看:https://my.oschina.net/esdn/blog/812417