zoukankan      html  css  js  c++  java
  • Django forms 定制form字段

    需求:

    采用forms可以快速生成html表单,并为后续views中的表单校验提供强大的功能,由于前端采用bootstrap实现样式,forms的默认字段并不具有bootstap相应的样式类,所以需要定制forms字段

    具体过程:

    为了使字段携带form-control样式

    forms.py:

    class CustomCharField(forms.CharField):
        def __init__(self, *, max_value=None, min_value=None, **kwargs):
            super().__init__(**kwargs)
            if not self.help_text:
                self.help_text = "0:不指定"
            self.initial = 0 #默认值为0,可以在后面的forms.Form中重新指定默认值
    
        def widget_attrs(self, widget):
            # 添加class样式写在这里,或者添加一些其他input属性都可以
            attrs = super().widget_attrs(widget)
            attrs["class"] = 'form-control form-control-sm'
            return attrs
    
    
    class CustomIntegerField(forms.IntegerField):
        def __init__(self, *, max_value=None, min_value=None, **kwargs):
            super().__init__(**kwargs)
            if not self.help_text:
                self.help_text = "0:不指定"
            self.initial = 0
    
        def widget_attrs(self, widget):
            attrs = super().widget_attrs(widget)
            attrs["class"] = 'form-control form-control-sm'
            return attrs
    
    class SearchForm(forms.Form):
        area = CustomCharField(label="区域", widget=forms.TextInput(attrs={"placeholder": "瓯海"}))
        package_name = CustomCharField(label="套餐名称", widget=forms.TextInput(attrs={"placeholder": "智享套餐"}))
        is_black = CustomCharField(label="是否黑名单", widget=forms.TextInput(attrs={"placeholder": "是/否"}))
        consume_three_average = CustomCharField(label="前三月平均消费区间",
                                                widget=forms.TextInput(attrs={"placeholder": "50-80"}))
        credit_score = CustomIntegerField(label="信用积分(大于)", widget=forms.NumberInput(attrs={"placeholder": 400}))
        final_guarantee_amount = CustomIntegerField(label="最终保底金额(大于)", widget=forms.NumberInput(attrs={"placeholder": 80}))
        level_start = CustomIntegerField(label="星级(大于)", widget=forms.NumberInput(attrs={"placeholder": 3}))
        active_info = CustomCharField(label="活动信息", widget=forms.TextInput(attrs={"placeholder": "幸福家128非合约"}))
        class_one_prepaid = CustomCharField(label="01类预缴(年月区间)", help_text="格式:'xxxx.xx-xxxx.xx',结果中包含“无01类预缴”;<br/>0:不指定",
                                               widget=forms.TextInput(attrs={"placeholder": '2021.06-2021.09'}))
        other_prepaid = CustomCharField(label="其他类预缴", help_text="默认排除",widget=forms.TextInput(attrs={"placeholder": "无其他预缴"}))
    
    
  • 相关阅读:
    Help-Web应用-.Net-Razor界面-入门-添加模型:在 ASP.NET Core 中向 Razor Pages 应用添加模型
    Help-Web应用-.Net-Razor界面-入门-教程:开始使用ASP.NET Core中的Razor Pages
    Help-Web应用-.Net-Razor界面-概述-教程:使用 ASP.NET Core 创建 Razor 页面 Web 应用
    白菜:奶白菜
    白菜:油白菜
    shell中&&和||的使用方法
    ISCSI测试
    iscsi共享分区测试
    RHEL7-openldap安装配置三(客户端自动挂载配置)
    redis配置笔记
  • 原文地址:https://www.cnblogs.com/lisicn/p/15397581.html
Copyright © 2011-2022 走看看