1.1 初识Form组件
基于注册为例来进行测试。
详细见示例:1-form组件.zip
1.2 错误信息
1.3 展示所有的字段
对象和可迭代对象。
1.4 问题:关于样式
-
手动操作
class RegisterForm(forms.Form): v1 = forms.CharField( label="手机号", required=True, # max_length=19, # min_length=6, initial="武沛齐", validators=[RegexValidator(r'^\d{11}$', "手机号格式错误"), ], widget=forms.TextInput(attrs={"class":"form-control"}) # <input type="text" class="form-control"/> ) v2 = forms.CharField( label="备注", required=True, widget=forms.Textarea(attrs={"class":"form-control"}) # <textarea class="form-control"/></textarea> ) ... .... .....
{% for field in form %} <p>{{ field.label }} {{ field }} {{ field.errors.0 }} </p> {% endfor %}
-
自动操作(找到每个字段中的widget插件,再找到插件中的attrs属性,给他每个赋值{"class":"form-control"}
class RegisterForm(forms.Form): v1 = forms.CharField(...,widget=forms.TextInput) v2 = forms.CharField(...,widget=forms.TextInput(attrs={"v1":"123"})) def __init__(self,*args,**kwargs): super().__init__(self,*args,**kwargs) for name,field in self.fields.items(): if name == "v1": continue if field.widget.attrs: field.widget.attrs.update({"class":"form-control"}) else: field.widget.attrs = {"class":"form-control"}
form = RegisterForm() # __init__ form = RegisterForm(data=request.POST) # __init__
1.5 问题:通用父类
class BootStrapForm(object):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for name, field in self.fields.items():
field.widget.attrs = {"class": "form-control"}
class LoginForm(BootStrapForm, forms.Form):
user = forms.CharField(label="用户名", widget=forms.TextInput)
pwd = forms.CharField(label="密码", widget=forms.TextInput)
def login(request):
form = LoginForm()
return render(request, "login.html", {"form": form})
class BootStrapForm(forms.Form):
def __init__(self, *args, **kwargs):
# 不是找父类
# 根据类的mro(继承关系),去找上个类
# super().__init__(*args, **kwargs)
for name, field in self.fields.items():
field.widget.attrs = {"class": "form-control"}
class LoginForm(BootStrapForm):
user = forms.CharField(label="用户名", widget=forms.TextInput)
pwd = forms.CharField(label="密码", widget=forms.TextInput)
def login(request):
form = LoginForm()
return render(request, "login.html", {"form": form})
标签:__,widget,Form,form,forms,field,组件,class
From: https://www.cnblogs.com/sherwin1995/p/18413784