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": "无其他预缴"}))

原文地址:https://www.cnblogs.com/lisicn/p/15397581.html