form 内置字段,数据实时更新,下拉框

用来验证 和 显示 生成html代码

类创建字段 使用参数

Field函数
    required=True,               是否允许为空
    widget=None,                 HTML插件
    label=None,                  用于生成Label标签或显示内容
    initial=None,                初始值
    help_text='',                帮助信息(在标签旁边显示)
    error_messages=None,         错误信息 {'required': '不能为空', 'invalid': '格式错误'}
    show_hidden_initial=False,   是否在当前插件后面再加一个隐藏的且具有默认值的插件(可用于检验两次输入是否一直)
    validators=[],               自定义验证规则
    localize=False,              是否支持本地化
    disabled=False,              是否可以编辑
    label_suffix=None            Label内容后缀

form 字段(用来匹配用户输入是否符合格式和设置HTML显示样式)

(正则匹配实现)

        ChoiceField                   # 下拉框 单选

        MultipleChoiceField     # 下拉框 多选

        CharField                       # 字符串

        IntegerField                   # 整型

        DecimalField                  #  浮点数设置 总长度 小数点后位数

        DateField                        # 时间类型     格式:2015-09-01

        DateTimeField                #格式:2015-09-01 11:12

        EmailField                        # 电子邮件格式

        GenericIPAddressField    # ip
        FileField                           # 文件上传
        

        RegexField                      # 自定义正则匹配


CharField(Field)
    max_length=None,             最大长度
    min_length=None,             最小长度
    strip=True                   是否移除用户输入空白
 
IntegerField(Field)
    max_value=None,              最大值
    min_value=None,              最小值
DecimalField(IntegerField)
    max_value=None,              最大值
    min_value=None,              最小值
    max_digits=None,             总长度
    decimal_places=None,         小数位长度
 
BaseTemporalField(Field)
    input_formats=None          时间格式化   
 
DateField(BaseTemporalField)    格式:2015-09-01
TimeField(BaseTemporalField)    格式:11:12
DateTimeField(BaseTemporalField)格式:2015-09-01 11:12
 
DurationField(Field)            时间间隔:%d %H:%M:%S.%f
    ...
 
RegexField(CharField)
    regex,                      自定制正则表达式
    max_length=None,            最大长度
    min_length=None,            最小长度
    error_message=None,         忽略,错误信息使用 error_messages={'invalid': '...'}
 
EmailField(CharField)      
    ...
 
FileField(Field)
    allow_empty_file=False     是否允许空文件
 
ImageField(FileField)      
    ...
    注:需要PIL模块,pip3 install Pillow
    以上两个字典使用时,需要注意两点:
        - form表单中 enctype="multipart/form-data"
        - view函数中 obj = MyForm(request.POST, request.FILES)
 
ChoiceField(Field)
    ...
    choices=(),                选项,如:choices = ((0,'上海'),(1,'北京'),)
    required=True,             是否必填
    widget=None,               插件,默认select插件
    label=None,                Label内容
    initial=None,              初始值
    help_text='',              帮助提示
 
 
ModelChoiceField(ChoiceField)
    ...                        django.forms.models.ModelChoiceField
    queryset,                  # 查询数据库中的数据
    empty_label="---------",   # 默认空显示内容
    to_field_name=None,        # HTML中value的值对应的字段
    limit_choices_to=None      # ModelForm中对queryset二次筛选
GenericIPAddressField
    protocol='both',           both,ipv4,ipv6支持的IP格式
    unpack_ipv4=False          解析ipv4地址,如果是::ffff:192.0.2.1时候,可解析为192.0.2.1, PS:protocol必须为both才能启用
 
SlugField(CharField)           数字,字母,下划线,减号(连字符)
    ...
 
UUIDField(CharField)           uuid类型

form 生成 HTML 

生成标签     自定制添加属性 attrs={,}


单选下拉框

radio  单选框

单select  单选下拉框


多选select  多选下拉框


checkbox  多选框



数据源实时更新



了解(设置样式时会很麻烦)



注意:依赖models中的str方法

代码

# 自定制插件  页面显示
# widget = widgets.TextInput(attrs={'class':'cls'})  input框添加类

    # 下拉框三种写法  多选
    from django.forms import widgets
    f = fields.CharField(
        widget=widgets.Select(choices=[(1,'上海'),(2,'北京')])
    )
    w = fields.IntegerField(
        widget = widgets.Select(choices=[(1,'上海'),(2,'北京')])
    )
    x = fields.ChoiceField(
        choices=[(1,'上海'),(2,'北京')],
    )

    # 单radio,值为字符串
    city = fields.CharField(
        initial=2,
        widget=widgets.RadioSelect(choices=((1,'上海'),(2,'北京'),))
    )

    # 单radio,值为字符串
    city = fields.ChoiceField(
        choices=((1, '上海'), (2, '北京'),),
        initial=2,
        widget=widgets.RadioSelect
    )

    # 单select,值为字符串
    city = fields.CharField(
        initial=2,
        widget=widgets.Select(choices=((1,'上海'),(2,'北京'),))
    )

    # 单select,值为字符串
    city = fields.ChoiceField(
        choices=((1, '上海'), (2, '北京'),),
        initial=2,
        widget=widgets.Select
    )

    # 多选select,值为列表
    city = fields.MultipleChoiceField(
        choices=((1,'上海'),(2,'北京'),),
        initial=[1,],
        widget=widgets.SelectMultiple
    )


    # 单checkbox
    city = fields.CharField(
        widget=widgets.CheckboxInput()
    )


    # 多选checkbox,值为列表
    city = fields.MultipleChoiceField(
        initial=[2, ],
        choices=((1, '上海'), (2, '北京'),),
        widget=widgets.CheckboxSelectMultiple
    )

数据源实时更新

from app01 import models
from django import forms
from django.forms import fields,widgets

class Users(forms.Form):
    age = fields.IntegerField()
    user_id = fields.IntegerField(
        # widget= widgets.Select(choices=models.Users.objects.values_list('id','username'))
        widget=widgets.Select(),
    )
    def __init__(self,*args,**kwargs):
        super(Users,self).__init__(*args,**kwargs)
        self.fields['user_id'].widget.choices = models.Users.objects.values_list('id','username')

def real(requset):
    obj = Users()
    return render(requset,'index.html',{'obj':obj}



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要实现下拉框实时更新,可以使用`tk.StringVar()`和`tk.OptionMenu()`函数。首先,创建一个`tk.StringVar()`类型的变量来存储下拉框中的选项,然后将其传递给`tk.OptionMenu()`函数。在更新下拉框的选项时,只需要更新`tk.StringVar()`变量的值即可。 以下是一个简单的例子,当点击按钮时,下拉框中的选项会实时更新: ```python import tkinter as tk root = tk.Tk() # 创建一个StringVar变量来存储下拉框中的选项 options = tk.StringVar(value='Option 1') # 创建一个OptionMenu并将options变量传递给它 option_menu = tk.OptionMenu(root, options, 'Option 1', 'Option 2', 'Option 3') option_menu.pack() # 定义一个函数来更新下拉框的选项 def update_options(): # 更新选项值 options.set('Option 4') # 更新OptionMenu中的选项 option_menu['menu'].delete(0, 'end') for option in ['Option 4', 'Option 5', 'Option 6']: option_menu['menu'].add_command(label=option, command=tk._setit(options, option)) # 创建一个按钮,点击它时更新下拉框的选项 button = tk.Button(root, text='Update Options', command=update_options) button.pack() root.mainloop() ``` 在这个例子中,我们首先创建了一个`tk.StringVar()`类型的变量`options`,并将其传递给了`tk.OptionMenu()`函数。然后,我们定义了一个`update_options()`函数,该函数会更新`options`变量的值,并使用`delete()`和`add_command()`方法更新`OptionMenu`中的选项。最后,我们创建了一个按钮,并将`update_options()`函数与它绑定,以实现点击按钮时更新下拉框的选项。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值