博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
django ---forms组件
阅读量:5286 次
发布时间:2019-06-14

本文共 9340 字,大约阅读时间需要 31 分钟。

本文目录

1 校验字段功能

 

针对一个实例:注册用户讲解。

 

模型:models.py

 

class UserInfo(models.Model):    name=models.CharField(max_length=32)    pwd=models.CharField(max_length=32)    email=models.EmailField( 模版文件
复制代码    
Title
{% csrf_token %}

视图函数:
# forms组件from django.forms import widgetswid_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())

2 渲染标签功能

 

渲染方式1

 

  
Title

注册页面

{% csrf_token %}
{ { form.name }}
{ { form.pwd }}
{ { form.r_pwd }}
{ { form.email }}

 

渲染方式2

 

{% csrf_token %} {% for field in form %}
{ { field }}
{% endfor %}

 

渲染方式3

 

{% csrf_token %} { { form.as_p }}

 

3 渲染错误信息功能

 

视图

 

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())

 

模板

 

{% csrf_token %} {% for field in form %}
{ { field }}
{ { field.errors.0 }}
{% endfor %}

 

4 组件的参数配置

 

class Ret(Form):    name = forms.CharField(max_length=10, min_length=2, label='用户名',                           error_messages={
'required': '该字段不能为空', 'invalid': '格式错误', 'max_length': '太长', 'min_length': '太短'}, widget=widgets.TextInput(attrs={
'class':'form-control'})) pwd = forms.CharField(max_length=10, min_length=2, widget=widgets.PasswordInput(attrs={
'class':'form-control'})) email = forms.EmailField(label='邮箱', error_messages={
'required': '该字段不能为空', 'invalid': '格式错误'})

 

 

 

5 局部钩子

 

from django.core.exceptions import NON_FIELD_ERRORS, ValidationError def clean_name(self):        val=self.cleaned_data.get("name")        ret=UserInfo.objects.filter(name=val)        if not ret:            return val        else:            raise ValidationError("该用户已注册!")    def clean_tel(self):        val=self.cleaned_data.get("tel")        if len(val)==11:            return val        else:            raise  ValidationError("手机号格式错误")

 

 

6 全局钩子

 

def clean(self):        pwd=self.cleaned_data.get('pwd')        r_pwd=self.cleaned_data.get('r_pwd')        if pwd and r_pwd:            if pwd==r_pwd:                return self.cleaned_data            else:                raise ValidationError('两次密码不一致')        else:            return self.cleaned_data

 

pwd_err=my_form.errors.get('__all__')
from django import formsfrom django.forms import widgetsfrom app01.models import UserInfofrom django.core.exceptions import NON_FIELD_ERRORS, ValidationErrorclass UserForm(forms.Form):    name=forms.CharField(min_length=4,label="用户名",error_messages={
"required":"该字段不能为空"}, widget=widgets.TextInput(attrs={
"class":"form-control"}) ) pwd=forms.CharField(min_length=4,label="密码", widget=widgets.PasswordInput(attrs={
"class":"form-control"}) ) r_pwd=forms.CharField(min_length=4,label="确认密码",error_messages={
"required":"该字段不能为空"},widget=widgets.TextInput(attrs={
"class":"form-control"})) email=forms.EmailField(label="邮箱",error_messages={
"required":"该字段不能为空","invalid":"格式错误"},widget=widgets.TextInput(attrs={
"class":"form-control"})) tel=forms.CharField(label="手机号",widget=widgets.TextInput(attrs={
"class":"form-control"})) def clean_name(self): val=self.cleaned_data.get("name") ret=UserInfo.objects.filter(name=val) if not ret: return val else: raise ValidationError("该用户已注册!") def clean_tel(self): val=self.cleaned_data.get("tel") if len(val)==11: return val else: raise ValidationError("手机号格式错误") def clean(self): pwd=self.cleaned_data.get('pwd') r_pwd=self.cleaned_data.get('r_pwd') if pwd and r_pwd: if pwd==r_pwd: return self.cleaned_data else: raise ValidationError('两次密码不一致') else: return self.cleaned_data
myforms
from django.shortcuts import render,HttpResponse# Create your views here.from app01.myforms import *def reg(request):    if request.method=="POST":        print(request.POST)        #form=UserForm({"name":"yu","email":"123@qq.com","xxxx":"alex"})        form=UserForm(request.POST) # form表单的name属性值应该与forms组件字段名称一致        print(form.is_valid()) # 返回布尔值        if form.is_valid():            print(form.cleaned_data)  # {"name":"yuan","email":"123@qq.com"}        else:            print(form.cleaned_data)  # {"email":"123@qq.com"}            # print(form.errors)        # {"name":[".........."]}            # print(type(form.errors))  # ErrorDict            # print(form.errors.get("name"))            # print(type(form.errors.get("name")))    # ErrorList            # print(form.errors.get("name")[0])            #   全局钩子错误            #print("error",form.errors.get("__all__")[0])            errors=form.errors.get("__all__")            return render(request,"reg.html",locals())        '''        form.is_valid()   :返回布尔值        form.cleaned_data :{"name":"yuan","email":"123@qq.com"}        form.errors       :{"name":[".........."]}        '''    form=UserForm()    return render(request,"reg.html",locals())
视图函数
    
Title
{#

简单form

#} {##} {##} {#
#} {# {% csrf_token %}#} {#

用户名

#} {#

密码

#} {#

确认密码

#} {#

邮箱

#} {#

手机号

#} {#
#} {##} {#
#}

forms组件渲染方式1

{% csrf_token %}

{

{ form.name.label }} {
{ form.name }} { { form.name.errors.0 }}

{

{ form.pwd.label }} {
{ form.pwd }} { { form.pwd.errors.0 }}

确认密码 {

{ form.r_pwd }} { { form.r_pwd.errors.0 }}{ { errors.0 }}

邮箱 {

{ form.email }} { { form.email.errors.0 }}

手机号 {

{ form.tel }} { { form.tel.errors.0 }}

{#

forms组件渲染方式2

#} {##} {#
#} {# {% csrf_token %}#} {##} {# {% for field in form %}#} {##} {#
#} {#
#} {# {
{ field }}#} {#
#} {##} {# {% endfor %}#} {##} {#
#} {#
#} {##} {#

forms组件渲染方式3

#} {##} {#
#} {# {% csrf_token %}#} {##} {# {
{ form.as_p }}#} {##} {#
#} {#
#}
模版文件

 ------------https://www.cnblogs.com/liuqingzheng/articles/9509775.html

转载于:https://www.cnblogs.com/di2wu/p/10080731.html

你可能感兴趣的文章
C++中的unique函数
查看>>
小白学数据分析----->流失分析设计
查看>>
FontAwesome 奥森图标的学习
查看>>
request response cookie session
查看>>
NMON记录服务器各项性能数据
查看>>
未找到arm-linux-gcc解决办法
查看>>
统计Xcode项目代码行数
查看>>
认识 service worker
查看>>
第五次团队作业:项目展示
查看>>
C#面向对象(二):封装和继承
查看>>
range()函数
查看>>
少量标签下的模型
查看>>
HOJ-1005 Fast Food(动态规划)
查看>>
FasfDFS整合Java实现文件上传下载
查看>>
用Hadoop构建电影推荐系统
查看>>
[读码时间] 弹出层效果
查看>>
UVAL 4728 Squares(旋转卡壳)
查看>>
Ordered Fractions usaco
查看>>
web框架的概念
查看>>
Codeforces-733C-Epidemic in Monstropolis&&733D-Kostya the Sculptor(乱搞)
查看>>