Django Form组件
1 验证 2 生成HTML(保留上次输入内容) 3 初始化默认值FORM重点 -字段 ChoiceField 单选框 MultipleChoiceField 多选框 CharField IntegerField DecimalField 小数 DateField DateTimeField EmailField GenericIPAddressField IP RegexField 自定义正则-HTML插件
通过attrs(class="jj") 给字段添加属性
自定义字段时的views文件
from django.shortcuts import renderfrom django import formsfrom django.forms import fieldsfrom django.forms import widgetsclass TestForm(forms.Form): user = fields.CharField( required=False, max_length=12, min_length=3, error_messages={ "required":'不能为空'}, ) age = fields.IntegerField() email = fields.EmailField() city =fields.ChoiceField( choices=[(1,"北京"),(2,"上海"),(3,"广州"),], #单选下拉框 initial=2 ) gender =fields.CharField( widget=widgets.Select(choices=[(1,"男"),(2,"女"),]), #单选下拉框 选男不选女 initial=2 ) hobby=fields.CharField( widget=widgets.RadioSelect(choices=[(1,"男"),(2,"女"),]), #单选radio initial = 2, ) province=fields.MultipleChoiceField( choices=[(1,'安徽'),(2,'江苏'),(3,'广东')], #d多选下拉框 initial=[1,2] ) cc=fields.CharField( widget=widgets.CheckboxInput(), #单选checkbox ) dd=fields.MultipleChoiceField( #多选 checkbox initial=[2,], choices=((1,'a'),(2,'b'),(3,"c")), widget=widgets.CheckboxSelectMultiple )def test(request): if request.method == "GET": obj=TestForm() render(request,'test.html',{ "obj":obj}) if request.method == 'POST': obj =TestForm(request.POST) return render(request,'test.html',{ 'obj':obj})
对应的HTML文件
Title
对应的效果
----------------------------------------------------------------------
用单选下拉框是,下拉框内的内容需要从数据库中取,
如果直接去,浏览器会将数据库的内容加载然后存到内存。后期数据库更新时,浏览器也不会更新的,所以需要添加__int__()属性
from app01 import modelsclass LoveForm(forms.Form): price = fields.IntegerField() user_id = fields.IntegerField( # widget=widgets.Select(choices=[(0,'alex'),(1,'杨建'),(2,'刘昊辰')]) widget = widgets.Select() ) def __init__(self,*args,**kwargs): #实时根据数据库更新,每次运行时,都会执行__int__(),得到choices super(LoveForm, self).__init__(*args,**kwargs) self.fields['user_id'].widget.choices=models.UserInFo.objects.values_list('id','username')def love(request): obj=LoveForm() return render(request,'love.html',{ 'obj':obj})