django 初识forms组件
目录
校验字段功能
示例: 注册用户
模型:models.py
from django.db import models
# Create your models here.
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)
实验验证功能
views.py
from django.shortcuts import render,HttpResponse,redirect
from django import forms
# Create your views here.
class UserForm(forms.Form):
name=forms.CharField(min_length=4)
pwd=forms.CharField(min_length=4)
re_pwd=forms.CharField(min_length=4)
email=forms.EmailField()
tel=forms.CharField()
def register(request):
if request.method=='POST':
print(request.POST)
name=request.POST.get('name')
form=UserForm({'name':name,'email':'123qq.com'})
if form.is_valid():
print(form.cleaned_data) #如果信息正确,输出 {'name':'wang','email':'123@qq.com'}
else:
print(form.cleaned_data)
print(form.errors.get('email')[0])
print(form.errors.get('email'))
form=UserForm()
return render(request,'register.html',locals())
register.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>register</title>
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<form method="post">
<div class="container">
<div class="row">
{% csrf_token %}
<div class="form-group">
{# name: <input type="text" name="name" class="form-control">#}
name: {{ form.name }}
</div>
<div class="form-group">
{# email: <input type="text" name="email" class="form-control">#}
email: {{ form.email }}
</div>
<div>
<input type="submit" class="btn btn-default pull-right">
</div>
</div>
</div>
</form>
</body>
</html>
forms组件渲染标签
渲染方式一
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<h3>注册页面</h3>
<div class="container">
<div class="row">
<div class="col-md-6 col-lg-offset-3">
<form action="" method="post">
{% csrf_token %}
<div>
<label for="">用户名</label>
{{ form.name }}
</div>
<div>
<label for="">密码</label>
{{ form.pwd }}
</div>
<div>
<label for="">确认密码</label>
{{ form.re_pwd }}
</div>
<div>
<label for=""> 邮箱</label>
{{ form.email }}
</div>
<input type="submit" class="btn btn-default pull-right">
</form>
</div>
</div>
</div>
</body>
</html>
渲染方式二
<div class="container">
<div class="row">
<div class="col-md-6 col-lg-offset-3">
<form action="" method="post">
{% csrf_token %}
{% for field in form %}
<div>
<label for="">{{ field.label }}</label>
{{ field }}
</div>
{% endfor %}
<input type="submit" class="btn btn-default pull-right">
</form>
</div>
</div>
</div>
渲染方式三 (不推荐, 自定义样式不方便)
<form action="" method="post">
{% csrf_token %}
{{ form.as_p }} // forms组件自动渲染<p></p>标签
<input type="submit" class="btn btn-default pull-right">
</form>
forms组件渲染错误信息和参数配置
views.py
from django.shortcuts import render,HttpResponse,redirect
from django import forms
from django.forms import widgets,ValidationError
from app01.models import *
# Create your views here.
class UserForm(forms.Form):
name=forms.CharField(min_length=4,label='姓名',
error_messages={'required':'该字段不能为空'}, # 当字段为空时, 自定义显示错误内容
widget=widgets.TextInput(attrs={'class':'form-control'}) # 标签渲染加入form-control样式
)
pwd=forms.CharField(min_length=4,label='密码',
widget=widgets.TextInput(attrs={'class': 'form-control'}),
error_messages={'required': '该字段不能为空'},
)
re_pwd=forms.CharField(min_length=4,label='重新输入',
widget=widgets.TextInput(attrs={'class': 'form-control'}),
error_messages={'required': '该字段不能为空'},
)
email=forms.EmailField(label='邮箱',
widget=widgets.TextInput(attrs={'class': 'form-control'}),
error_messages={'required': '该字段不能为空','invalid':'格式不正确'},
)
tel=forms.CharField(label='电话',
widget=widgets.TextInput(attrs={'class': 'form-control'}),
error_messages={'required': '该字段不能为空'},
)
def register(request):
form=UserForm(request.POST)
if not form.is_valid():
errors=form.errors.get('__all__')
else:
form=UserForm()
return render(request,'register.html',locals())
forms组件校验的局部钩子( clean_字段名 )
views.py
from django.shortcuts import render,HttpResponse,redirect
from django import forms
from django.forms import widgets,ValidationError
from app01.models import *
# Create your views here.
class 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.TextInput(attrs={'class': 'form-control'}),
error_messages={'required': '该字段不能为空'},
)
re_pwd=forms.CharField(min_length=4,label='重新输入',
widget=widgets.TextInput(attrs={'class': 'form-control'}),
error_messages={'required': '该字段不能为空'},
)
email=forms.EmailField(label='邮箱',
widget=widgets.TextInput(attrs={'class': 'form-control'}),
error_messages={'required': '该字段不能为空','invalid':'格式不正确'},
)
tel=forms.CharField(label='电话',
widget=widgets.TextInput(attrs={'class': 'form-control'}),
error_messages={'required': '该字段不能为空'},
)
def clean_name(self): # 在forms类中添加一个方法,命名规则固定 clean_字段名
val=self.cleaned_data.get('name') # val固定, 写死的
ret=UserInfo.objects.filter(name=val)
if not ret:
return val # return val固定写死
else:
raise ValidationError('该用户已注册') # 不符合条件时触发ValidationError异常
def clean_tel(self):
val=self.cleaned_data.get('tel')
ret=len(val)
if ret == 11:
print('true')
return val
else:
raise ValidationError('格式不正确')
def register(request):
form=UserForm(request.POST)
if not form.is_valid():
errors=form.errors.get('__all__')
else:
form=UserForm()
return render(request,'register.html',locals())
forms组件校验的全局钩子 ( clean )
from django.shortcuts import render,HttpResponse,redirect
from django import forms
from django.forms import widgets,ValidationError
from app01.models import *
# Create your views here.
class 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.TextInput(attrs={'class': 'form-control'}),
error_messages={'required': '该字段不能为空'},
)
re_pwd=forms.CharField(min_length=4,label='重新输入',
widget=widgets.TextInput(attrs={'class': 'form-control'}),
error_messages={'required': '该字段不能为空'},
)
email=forms.EmailField(label='邮箱',
widget=widgets.TextInput(attrs={'class': 'form-control'}),
error_messages={'required': '该字段不能为空','invalid':'格式不正确'},
)
tel=forms.CharField(label='电话',
widget=widgets.TextInput(attrs={'class': 'form-control'}),
error_messages={'required': '该字段不能为空'},
)
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')
print(val)
ret=len(val)
print(ret)
if ret == 11:
print('true')
return val
else:
raise ValidationError('格式不正确')
def clean(self): # 命名固定为clean
pwd=self.cleaned_data.get('pwd')
re_pwd=self.cleaned_data.get('re_pwd')
if pwd and re_pwd:
if pwd == re_pwd:
return self.cleaned_data # 符合规则, 返回self.cleaned_data
else:
raise ValidationError('两次密码不一致') # 不符合规则, 触发ValidationError异常
else:
return self.cleaned_data
def register(request):
if request.method=='POST':
form=UserForm(request.POST)
if not form.is_valid():
errors=form.errors.get('__all__')
else:
form=UserForm()
return render(request,'register.html',locals())