forms组件如何在Django中使用-创新互联
这篇文章将为大家详细讲解有关forms组件如何在Django中使用,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。
成都创新互联公司主营惠山网站建设的网络公司,主营网站建设方案,app开发定制,惠山h5微信小程序搭建,惠山网站营销推广欢迎惠山等地区企业咨询一,forms组件:
校验字段功能
针对一个实例:注册用户讲解。
模型:models.py
class UserInfo(models.Model): name=models.CharField(max_length=32) pwd=models.CharField(max_length=32) email=models.EmailField() tel=models.CharField(max_length=32)
模板: register.html:
Title
视图函数:register
# forms组件 from django.forms import widgets wid_01=widgets.TextInput(attrs={"class":"form-control"}) wid_02=widgets.PasswordInput(attrs={"class":"form-control"}) class UserForm(forms.Form): name=forms.CharField(max_length=32, widget=wid_01 ) pwd=forms.CharField(max_length=32,widget=wid_02) r_pwd=forms.CharField(max_length=32,widget=wid_02) email=forms.EmailField(widget=wid_01) tel=forms.CharField(max_length=32,widget=wid_01) def register(request): if request.method=="POST": form=UserForm(request.POST) if form.is_valid(): print(form.cleaned_data) # 所有干净的字段以及对应的值 else: print(form.cleaned_data) # print(form.errors) # ErrorDict : {"校验错误的字段":["错误信息",]} print(form.errors.get("name")) # ErrorList ["错误信息",] return HttpResponse("OK") form=UserForm() return render(request,"register.html",locals())
1,渲染标签功能
渲染方式1
Title 注册页面
渲染方式2
渲染方式3
2,显示错误与重置输入信息功能
视图
def register(request): if request.method=="POST": form=UserForm(request.POST) if form.is_valid(): print(form.cleaned_data) # 所有干净的字段以及对应的值 else: print(form.cleaned_data) # print(form.errors) # ErrorDict : {"校验错误的字段":["错误信息",]} print(form.errors.get("name")) # ErrorList ["错误信息",] return render(request,"register.html",locals()) form=UserForm() return render(request,"register.html",locals())
模板
3,局部钩子与全局钩子
模板
# forms组件 from django.forms import widgets wid_01=widgets.TextInput(attrs={"class":"form-control"}) wid_02=widgets.PasswordInput(attrs={"class":"form-control"}) from django.core.exceptions import ValidationError class UserForm(forms.Form): name=forms.CharField(max_length=32, widget=wid_01 ) pwd=forms.CharField(max_length=32,widget=wid_02) r_pwd=forms.CharField(max_length=32,widget=wid_02) email=forms.EmailField(widget=wid_01) tel=forms.CharField(max_length=32,widget=wid_01) # 局部钩子 def clean_name(self): val=self.cleaned_data.get("name") if not val.isdigit(): return val else: raise ValidationError("用户名不能是纯数字!") # 全局钩子 def clean(self): pwd=self.cleaned_data.get("pwd") r_pwd=self.cleaned_data.get("r_pwd") if pwd==r_pwd: return self.cleaned_data else: raise ValidationError('两次密码不一致!') def register(request): if request.method=="POST": form=UserForm(request.POST) if form.is_valid(): print(form.cleaned_data) # 所有干净的字段以及对应的值 else: clean_error=form.errors.get("__all__") return render(request,"register.html",locals()) form=UserForm() return render(request,"register.html",locals())
视图
关于forms组件如何在Django中使用就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
网站标题:forms组件如何在Django中使用-创新互联
分享链接:http://cdiso.cn/article/hoedo.html