共计 2634 个字符,预计需要花费 7 分钟才能阅读完成。
####1、ModelFrom 能够主动生成 HTML 标签
1.1 主动生成 ID, 格局为 ID_
models.py
create_time = models.DateField(verbose_name='入职工夫')
HTML
id="id_create_time"
<input type="text" name="create_time" class="form-control" placeholder="入职工夫" required=""id="id_create_time">
-
ModelForm 能够帮忙咱们生成 HTML 标签。
class UserModelForm(forms.ModelForm): class Meta: model = models.UserInfo fields = ["name", "password",] form = UserModelForm()
{{form.name}} 一般的 input 框 {{form.password}} 一般的 input 框
-
定义插件
class UserModelForm(forms.ModelForm): class Meta: model = models.UserInfo fields = ["name", "password",] widgets = {"name": forms.TextInput(attrs={"class": "form-control"}), "password": forms.PasswordInput(attrs={"class": "form-control"}), "age": forms.TextInput(attrs={"class": "form-control"}), }
class UserModelForm(forms.ModelForm): name = forms.CharField( min_length=3, label="用户名", widget=forms.TextInput(attrs={"class": "form-control"}) ) class Meta: model = models.UserInfo fields = ["name", "password", "age"]
{{form.name}} BootStrap 的 input 框 {{form.password}} BootStrap 的 input 框
-
从新定义的 init 办法,批量设置
class UserModelForm(forms.ModelForm): class Meta: model = models.UserInfo fields = ["name", "password", "age",] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # 循环 ModelForm 中的所有字段,给每个字段的插件设置 for name, field in self.fields.items(): field.widget.attrs = { "class": "form-control", "placeholder": field.label }
class UserModelForm(forms.ModelForm): class Meta: model = models.UserInfo fields = ["name", "password", "age",] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # 循环 ModelForm 中的所有字段,给每个字段的插件设置 for name, field in self.fields.items(): # 字段中有属性,保留原来的属性,没有属性,才减少。if field.widget.attrs: field.widget.attrs["class"] = "form-control" field.widget.attrs["placeholder"] = field.label else: field.widget.attrs = { "class": "form-control", "placeholder": field.label }
class UserEditModelForm(forms.ModelForm): class Meta: model = models.UserInfo fields = ["name", "password", "age",] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # 循环 ModelForm 中的所有字段,给每个字段的插件设置 for name, field in self.fields.items(): # 字段中有属性,保留原来的属性,没有属性,才减少。if field.widget.attrs: field.widget.attrs["class"] = "form-control" field.widget.attrs["placeholder"] = field.label else: field.widget.attrs = { "class": "form-control", "placeholder": field.label }
-
自定义类
class BootStrapModelForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # 循环 ModelForm 中的所有字段,给每个字段的插件设置 for name, field in self.fields.items(): # 字段中有属性,保留原来的属性,没有属性,才减少。if field.widget.attrs: field.widget.attrs["class"] = "form-control" field.widget.attrs["placeholder"] = field.label else: field.widget.attrs = { "class": "form-control", "placeholder": field.label }
class UserEditModelForm(BootStrapModelForm): class Meta: model = models.UserInfo fields = ["name", "password", "age",]
正文完