首页 > 技术文章 > 常用form及当在数据库添加后及时更新

wenghao 2019-08-13 11:08 原文

form中fields包含正则表达式和html中的插件(会访问__str__方法返回一个html文件),插件可以通过wieget这个参数进行修改

为字符串的选择框
xdb=fields.CharField(
widget=widgets.Select(choices=[(1,'上海',),(2,'北京'),(3,'沙河')])
)

Form重点:
- 字段
用于保存正则表达式
ChoiceField *****
MultipleChoiceField
CharField
IntegerField
DecimalField
DateField
DateTimeField
EmailField
GenericIPAddressField
FileField

RegexField
- HTML插件
用于生成HTML标签

- 特殊的单选或多选时,数据源是否能实时更新?????*****
from app01 import models
class 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):
super(LoveForm,self).__init__(*args,**kwargs)
self.fields['user_id'].widget.choices = models.UserInfo.objects.values_list('id','username')

from django.forms.models import ModelChoiceField
from django.forms.models import ModelChoiceField
class LoveForm(forms.Form):
price = fields.IntegerField()

user_id2 = ModelChoiceField(
queryset=models.UserInfo.objects.all(),
to_field_name='id'
)

注意:依赖models中的str方法

推荐阅读