Django学习——分页器基本使用、分页器终极用法、forms组件之校验字段、forms组件之渲染标签、forms组件全局钩子,局部钩子
内容
1 分页器基本使用
2 分页器终极用法
3 forms组件之校验字段
1 前端
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<form action="" method="post">
<p>用户名:<input type="text" name="name"></p>
<p>密码:<input type="password" name="password"></p>
<p>确认密码:<input type="password" name="re_password"></p>
<p>邮箱:<input type="text" name="email"></p>
<input type="submit" value="提交">
</form>
</body>
</html>
2 后端
# forms的使用
# 第一步:定义一个类,继承
# 第二版:在类中写字段,要校验的字段,字段属性就是校验规则
# 第三步:实例化得到一个Form对象,把要校验的数据传入
# 第四步:调用register_form.is_valid()校验,校验通过就是True
# 第五步:校验通过有register_form.cleaned_data
# 第六步:校验不通过有register_form.errors
from django import forms
from app01 import models
class RegisterForm(forms.Form):
name = forms.CharField(max_length=8,min_length=3)
password = forms.CharField(max_length=8,min_length=3)
re_password = forms.CharField(max_length=8,min_length=3)
email = forms.EmailField()
def register(request):
if request.method == 'GET':
return render(request,'register.html')
else:
# 实例化得到对象,传入要校验的数据
# register_form = RegisterForm(data=request.POST)
register_form = RegisterForm(request.POST)
if register_form.is_valid():
# 校验通过,存
# 取出校验通过的数据
print('校验通过')
print(register_form.cleaned_data)
register_form.cleaned_data.pop('re_password')
models.User.objects.create(**register_form.cleaned_data)
else:
# 校验不通过
print('校验不通过')
print(register_form.errors)
return HttpResponse('ok')
4 forms组件之渲染标签
1 前端
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<h1>自己写</h1>
<form action="" method="post">
<p>用户名:<input type="text" name="name"></p>
<p>密码:<input type="password" name="password"></p>
<p>确认密码:<input type="password" name="re_password"></p>
<p>邮箱:<input type="text" name="email"></p>
<input type="submit" value="提交">
</form>
<hr>
<h2>通过form自动渲染一</h2>
<form action="" method="post">
<p>用户名:{{ form.name }}</p>
<p>密码:{{ form.password }}</p>
<p>确认密码:{{ form.re_password }}</p>
<p>邮箱:{{ form.email }}</p>
<input type="submit" value="提交">
</form>
<hr>
<h2>通过form自动渲染二(基本用这种)</h2>
<form action="" method="post">
{% for item in form %}
<p>{{ item.label }}:{{ item }}</p>
{% endfor %}
<input type="submit" value="提交">
</form>
<hr>
<h2>通过form自动渲染三</h2>
<form action="" method="post">
{{ form.as_p }}
{# {{ form.as_ul }}#}
<input type="submit" value="提交">
</form>
</body>
</html>
2 后端 views
from django import forms
from app01 import models
class RegisterForm(forms.Form):
name = forms.CharField(max_length=8,min_length=3,label='用户名')
password = forms.CharField(max_length=8,min_length=3,label='密码')
re_password = forms.CharField(max_length=8,min_length=3,label='确认密码')
email = forms.EmailField(label='邮箱')
def register(request):
if request.method == 'GET':
# 生成一个空form对象
register_form = RegisterForm()
return render(request,'register.html',{'form':register_form})
else:
# 实例化得到对象,传入要校验的数据
# register_form = RegisterForm(data=request.POST)
register_form = RegisterForm(request.POST)
if register_form.is_valid():
# 校验通过,存
# 取出校验通过的数据
print('校验通过')
print(register_form.cleaned_data)
register_form.cleaned_data.pop('re_password')
models.User.objects.create(**register_form.cleaned_data)
else:
# 校验不通过
print('校验不通过')
print(register_form.errors)
return HttpResponse('ok')
5 forms组件之渲染错误信息
6 forms组件参数设置
7 forms组件全局钩子,局部钩子
1 后端
# forms的使用
# 第一步:定义一个类,继承
# 第二版:在类中写字段,要校验的字段,字段属性就是校验规则
# 第三步:实例化得到一个Form对象,把要校验的数据传入
# 第四步:调用register_form.is_valid()校验,校验通过就是True
# 第五步:校验通过有register_form.cleaned_data
# 第六步:校验不通过有register_form.errors
from django import forms
from app01 import models
from django.forms import widgets
from django.core.exceptions import ValidationError
class RegisterForm(forms.Form):
name = forms.CharField(max_length=8, min_length=3, label='用户名',
error_messages={'max_length': '最大长度为8', 'min_length': '最小长度为3', 'required': '该字段必填'},
widget=widgets.TextInput(attrs={'class':'form-control'}))
password = forms.CharField(max_length=8, min_length=3, label='密码',
error_messages={'max_length': '最大长度为8', 'min_length': '最小长度为3', 'required': '该字段必填'},
widget=widgets.PasswordInput(attrs={'class':'form-control'}))
re_password = forms.CharField(max_length=8, min_length=3, label='确认密码',
error_messages={'max_length': '最大长度为8', 'min_length': '最小长度为3', 'required': '该字段必填'},
widget=widgets.PasswordInput(attrs={'class':'form-control'}))
email = forms.EmailField(label='邮箱', error_messages={'required': '该字段必填', 'invalid': '邮箱格式错误'},widget=widgets.TextInput(attrs={'class':'form-control'}))
def clean_name(self): # name字段的局部钩子
# 校验名字不能以sb开头
name = self.cleaned_data.get('name')
if name.startswith('sb'):
# 校验不通过,必须抛异常
raise ValidationError('不能以sb开头')
else: # 校验通过,返回name对应的值
return name
def clean(self): # 全局钩子
password = self.cleaned_data.get('password')
re_password = self.cleaned_data.get('re_password')
if re_password == password:
# 校验通过
return self.cleaned_data
else:
raise ValidationError('两次密码不一致')
def register(request):
if request.method == 'GET':
# 生成一个空form对象
register_form = RegisterForm()
return render(request, 'register.html', {'form': register_form})
else:
# 实例化得到对象,传入要校验的数据
# register_form = RegisterForm(data=request.POST)
register_form = RegisterForm(request.POST)
if register_form.is_valid():
# 校验通过,存
# 取出校验通过的数据
print('校验通过')
print(register_form.cleaned_data)
register_form.cleaned_data.pop('re_password')
models.User.objects.create(**register_form.cleaned_data)
return HttpResponse('ok')
else:
# 校验不通过
print('校验不通过')
print(register_form.errors)
error = register_form.errors.get('__all__')[0]
return render(request, 'register.html', {'form': register_form,'error':error})
# <ul class="errorlist"><li>name<ul class="errorlist"><li>Ensure this value has at least 3 characters (it has 1).</li></ul></li></ul>
2 前端
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<h1>自己写</h1>
<form action="" method="post">
<p>用户名:<input type="text" name="name"></p>
<p>密码:<input type="password" name="password"></p>
<p>确认密码:<input type="password" name="re_password"></p>
<p>邮箱:<input type="text" name="email"></p>
<input type="submit" value="提交">
</form>
<hr>
<h2>通过form自动渲染一</h2>
<form action="" method="post">
<p>用户名:{{ form.name }}</p>
<p>密码:{{ form.password }}</p>
<p>确认密码:{{ form.re_password }}</p>
<p>邮箱:{{ form.email }}</p>
<input type="submit" value="提交">
</form>
<hr>
<h2>通过form自动渲染二(基本用这种)</h2>
<div class="container-fluid">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<form action="" method="post" novalidate>
{% for item in form %}
<div class="form-group">
<p>{{ item.label }}:{{ item }} <span style="color: red">{{ item.errors.0 }}</span></p>
</div>
{% endfor %}
<input type="submit" value="提交"><span style="color: red">{{ error }}</span>
</form>
</div>
</div>
</div>
<hr>
<h2>通过form自动渲染三</h2>
<form action="" method="post">
{{ form.as_p }}
{# {{ form.as_ul }}#}
<input type="submit" value="提交">
</form>
</body>
</html>
Django设置响应头
代码review 保证软件质量
回顾
1 分页
-Django提供的两个类
-Paginator类 page对象
-Page类
2 forms组件
-数据校验
-渲染页面
-错误信息
-局部全局钩子
-使用步骤:
-写一个类,继续Form类
-写字段,字段参数(限制该字段的长短)
-错误信息中文:字段参数
-widget:控制生成标签的属性
-视图函数中:
-实例化得到form对象时,把要校验的数据传入
-is_valiad():clean_data和errors就有值了 即便校验出错clean_data 也可能有值
-如果校验通过就存,不通过就给页面提示
-渲染页面
-for循环的方式渲染页面(在标签前后可以再加标签)
-局部钩子
- def clean_字段名(self):
-检验规则
-如果通过,return 值
-如果不通过,抛异常
-全局钩子(多个字段校验)
-def clean(self):
-如果通过,return clean_data
-如果不通过,抛异常
本文来自博客园,作者:寻月隐君,转载请注明原文链接:https://www.cnblogs.com/QiaoPengjun/p/16260415.html