django--form组件
- 对用户请求的验证
- 生产HTML代码
- 初始化默认值
- form表单
ChoiceField
MultipleChoiceField
CharField
IntegerField
DecimalField
DataField
DataTimeField
EmailField
GenericIPAdressField
FileFeild
RegexField
单选select框 2种写法
单选select,值为字符串
s = fields.CharField(
initial =2,
widget = widgets.Select(choices=[(1,'上海'),(2,‘北京’)])
)
单选select,值为数值
s = fields.IntegerField(
initial =2,
widget = widgets.Select(choices=[(1,'上海'),(2,‘北京’)])
)
单select,值为字符串
s=fields.ChoiceField(
choices = [(1,'上海'),(2,‘北京’),(2,‘北京’)],
initial = 2,
widget = widjets.Select
)
m = fields.MultipleChoiceField(
choices = [(1,'上海'),(2,‘北京’),(3,‘深圳’)],
widget = widgets.SelectMultiple(attrs={'class':'c1'})
)
c = fields.CharField(
widget = widgets.CheckboxInput()
)
c = fields.MultipleChoiceField(
initial = [2,]
choices = ((1,'上海'),(2,'北京'),),
widget = widgets.CheckboxSelectMultiple()
)
r = fields.ChoiceField(
initial = [2,]
choices = ((1,'上海'),(2,'北京'),),
widget = widgets.RadioSelect()
)
r = fields.CharField(
widget = widgets.RadioSelect(choices = ((1,'上海'),(2,'北京'),))
)
从数据库每次重新启动程序
class AForm(forms.Form):
price = fields.IntegerField()
user_id = fieldss.IntegerField(
widget = widgets.Select()
)
def __init(self,*args,**kwargs):
super(LoveForm,self).__init__(*args,**kwargs)
self.fields['user_id'].widget.choices = models.UserInfo.object.values_list('id','username')
def a(request):
obj = AForm()
redr
views.py 代码
from django.shortcuts import render from django import forms from django.forms import fields from django.forms import widgets class TestForm(forms.Form): user = fields.CharField( required=True, #是否必填 max_length=12, #最大长度 min_length=3,#最小长度 # error_messages={ }, widget = widgets.Select(),# 定制HTML label="用户名" ) age = fields.IntegerField( label="年龄" ) email = fields.EmailField( label="邮件" ) def test(requset): obj = TestForm() return render(requset,'test.html',{"obj":obj})
html 代码
<html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <p>{{ obj.user.label }}{{ obj.user }}</p> <p>{{ obj.user.age }}{{ obj.age }}</p> <p>{{ obj.user.email }}{{ obj.email }}</p> </body> </html>
页面展示
Django内置字段如下: