## 1 forms渲染错误信息 ```python 1 form对象.errors 字典 2 name对象.errors ## 视图函数 def register(request): if request.method=='GET': form=myforms.MyForm() return render(request, 'register.html',{'form':form}) else: form=myforms.MyForm(request.POST) if form.is_valid(): return redirect('http://www.baidu.com') else: return render(request, 'register.html',{'form':form}) ## 模板 <form action="" method="post" novalidate> {% for foo in form %} <div class="form-group"> <label for="">{{ foo.label }}</label> {{ foo }} <span class="text-danger pull-right">{{ foo.errors }}</span> </div> {% endfor %} <div class="text-center"> <input type="submit" value="提交" class="btn btn-danger"> </div> </form> ``` ## 2 forms组件参数配置 ```python # 定制模板中的显示样式,及配置类 # widget=widgets.PasswordInput(attrs={'class': 'form-control'}) # 错误信息中文显示 error_messages={'min_length': '太短了小伙子'} class MyForm(forms.Form): # 校验这个字段,最大长度是32,最小长度是3 name = forms.CharField(required=False, max_length=32, min_length=3, label='用户名', widget=widgets.TextInput(attrs={'class': 'form-control'}), error_messages={'min_length': '太短了小伙子'}) password = forms.CharField(required=False, max_length=32, min_length=3, label='密码', widget=widgets.PasswordInput(attrs={'class': 'form-control'}), error_messages={'min_length': '太短了小伙子'}) re_password = forms.CharField(required=False, max_length=32, min_length=3, label='确认密码', widget=widgets.PasswordInput(attrs={'class': 'form-control'}), error_messages={'min_length': '太短了小伙子'}) email = forms.EmailField(label='邮箱', error_messages={'required': '小惠子,这个必填'}, widget=widgets.TextInput(attrs={'class': 'form-control'})) age = forms.IntegerField(max_value=200, min_value=0, label='年龄', widget=widgets.TextInput(attrs={'class': 'form-control'})) text = forms.CharField(label='个人简介', widget=widgets.Textarea(attrs={'class': 'form-control'})) date = forms.CharField(label='出生日期', widget=widgets.DateInput(attrs={'class': 'form-control'})) ``` ## 3 局部钩子和全局钩子 ```python ## 局部钩子的使用 # 1 在自定义的Form类中写 clean_字段名 # 2 取出字段的真正值,name=self.cleaned_data.get('name') # 3 判断自己的规则,如果判断失败,抛出ValidationError # 4 如果通过,return name # 局部钩子 def clean_name(self): # name对应的值,如何取到? name = self.cleaned_data.get('name') if name.startswith('sb'): # 不让校验通过 raise ValidationError('不能以sb开头') else: # 校验通过,返回name return name # 全局钩子 def clean(self): # name=self.cleaned_data.get('name') # print(name) password = self.cleaned_data.get('password') re_password = self.cleaned_data.get('re_password') if password == re_password: return self.cleaned_data # return {'lqz':"nb"} else: raise ValidationError('两次密码不一致') ``` ## 4 cookie session token ```python 1 https://www.cnblogs.com/liuqingzheng/articles/8990027.htmlp 2 cookie: 保存在客户端浏览器上的键值对 3 session:保存在服务端的键值对 4 token:加密的键值对,如果放在客户端浏览器上,它就叫cookie, 服务端签发的加密字符串 head.{name:lqz,age:18}.eseetsweasdca base64加码: asdfasfd.asdfasdf.asdfasdfaeraew 后端校验: 用这个token去查我的账户余额,向银行发请求,银行校验通过,是银行给你的,---》返回你的余额 head.{name:lqz,age:18}.eseetsweasdca head.{name:egon,age:18}.eseetsweasdca ``` ## 5 django中cookie的使用 ```python def cookie_test(request): # 浏览器向我这个地址发一个请求,就在浏览器写入 name = lqz obj=HttpResponse('ok') obj.set_cookie('name','egon') # 写入到浏览器了,在http响应头里:cookie: name=lqz obj.set_cookie('age','19') # 写入到浏览器了,在http响应头里:cookie: name=lqz return obj def get_cookie(request): print(request.COOKIES) print(request.COOKIES.get('name')) return HttpResponse('我拿了你传过来的cookie') def delete_cookie(request): obj=HttpResponse('我删掉了你 name 这个cookie ') obj.delete_cookie('name') return obj ```
# views.py from django.shortcuts import render, HttpResponse, redirect from app01 import app01_forms # Create your views here. def register(request): if request.method == 'GET': form = app01_forms.MyForm() return render(request, 'register.html', {'form': form}) else: form = app01_forms.MyForm(request.POST) if form.is_valid(): print(form.cleaned_data) return HttpResponse('校验通过。') else: error = form.errors.get('__all__') print(error) return render(request, 'register.html', {'form': form, 'error': error}) def add_cookie(request): obj = HttpResponse('add_cookie') obj.set_cookie('name','welt') # set_cookie('key','value') 添加 或 修改 cookie return obj def get_cookie(request): print(request.COOKIES) # 获取cookie print(request.COOKIES.get('name')) # 获取cookie return HttpResponse('获取cookie') def del_cookie(request): obj = HttpResponse('删除cookie') obj.delete_cookie('name') # HttpResponse对象.delete_cookie('key') 删除cookie return obj
# app01_forms.py from django import forms from django.forms import widgets, ValidationError class MyForm(forms.Form): username = forms.CharField(max_length=32, min_length=3, required=True, label='用户名', widget=widgets.TextInput(attrs={'class': 'form-control'}), error_messages={'required': '用户名不能为空!', 'min_length': '长度不少于3位!'}) # error_messages控制错误类型对应的错误信息 # 先导入:from django.forms import widgets # widget 控制渲染模板时生成的输入框类型,括号中可以为标签添加属性,例:attrs={'class': 'form-control'} --> 添加一个form-control类 password = forms.CharField(max_length=32, min_length=5, label='密码', widget=widgets.PasswordInput(attrs={'class': 'form-control'}), error_messages={'required': '密码不能为空!', 'min_length': '长度不少于5位!'}) re_password = forms.CharField(max_length=32, min_length=5, label='密码', widget=widgets.PasswordInput(attrs={'class': 'form-control'}), error_messages={'required': '密码不能为空!', 'min_length': '长度不少于5位!'}) email = forms.EmailField(max_length=32, label='邮箱', widget=widgets.TextInput(attrs={'class': 'form-control'})) age = forms.IntegerField(max_value=200, required=False, label='年龄', widget=widgets.TextInput(attrs={'class': 'form-control'})) text = forms.CharField(max_length=200, label='个人简介', required=False, widget=widgets.Textarea(attrs={'class': 'form-control'})) birthday = forms.DateField(label='出生日期', widget=widgets.DateInput(attrs={'type': 'date', 'class': 'form-control'}), required=False) # 局部钩子(方法,方法名:clean_字段名) # 高级校验:例:name不能以sb开头 def clean_username(self): # 只要程序能走到这个方法,则表示前面该字段的校验已经通过 name = self.cleaned_data.get('username') # 通过cleaned_data获取当前对象的username if name.startswith('sb'): raise ValidationError('用户名不能以sb开头!') else: return name # 全局钩子 def clean(self): # 只要程序能走到这个方法,则表示前面的校验以及局部钩子都已经通过 password = self.cleaned_data.get('password') re_password = self.cleaned_data.get('re_password') if password == re_password: return self.cleaned_data else: raise ValidationError('密码不一致!') # 全局钩子的raise错误通过views中的对应函数使用form.errors.get('__all__')来获取,并传到前端显示
// register.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css"> <title>Title</title> </head> <body> <hr> <div class="container-fluid"> <div class="row"> <div class="col-md-6 col-md-offset-3"> <h1>半自动渲染模板3(用的最多)</h1> <form action="" method="post" novalidate> <!--novalidate取消前端校验--> {% for foo in form %} <div class="form-group"> <label for="">{{ foo.label }}</label> {{ foo }} <span class="text-danger pull-right">{{ foo.errors }}</span> <!--每一个foo都有自己的errors属性--> </div> {% endfor %} <div class="text-center"> <input type="submit" value="提交" class="btn btn-danger"> <span class="text-primary">{{ error }}</span> </div> </form> </div> </div> </div> </body> </html>