day19-Django2
1、Form验证
- 用于做用户提交数据的验证
a. 定义规则(类,**字段名=html中name值,必须一致)
b. 数据提交 - 规则 匹配
from django.shortcuts import render,HttpResponse # Create your views here. from django import forms from django.core.exceptions import ValidationError import re def mobile_validate(value): mobile_re = re.compile(r'^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$') if not mobile_re.match(value): raise ValidationError('手机号码格式错误') class LoginForm(forms.Form): user = forms.CharField(required=True, error_messages={'required': '用户名不能为空.'}) pwd = forms.CharField(required=True, min_length=6, max_length=10, error_messages={'required': '密码不能为空.', 'min_length': "至少6位"}) num = forms.IntegerField(error_messages={'required': '数字不能空.','invalid': '必须输入数字'}) phone = forms.CharField(validators=[mobile_validate, ],) import json def login(request): if request.method == 'POST': result = {'status': False, 'message': None} obj = LoginForm(request.POST) ret = obj.is_valid() if ret: print(obj.clean()) result['status'] = True else: from django.forms.utils import ErrorDict #print(type(obj.errors),obj.errors.as_json()) error_str = obj.errors.as_json() result['message'] = json.loads(error_str) return HttpResponse(json.dumps(result)) return render(request, 'login.html')
-
用于做用户提交数据的验证 + 生成HTML标签
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <style> .error-msg{ color: red; } </style> </head> <body> <div> <div> <input type="text" name="user" /> </div> <div> <input type="password" name="pwd" /> </div> <div> <input type="text" name="num" /> </div> <div> <input type="text" name="phone" /> </div> <input type="button" value="提交" onclick="DoSubmit();" /> </div> <script src="/static/jquery-2.1.4.min.js"></script> <script> function DoSubmit(){ var input_dict = {}; $('input').each(function(){ var v = $(this).val(); var n = $(this).attr('name'); input_dict[n] = v; }); console.log(input_dict); $('.error-msg').remove(); $.ajax({ url: '/login/', type: 'POST', data: input_dict, dataType: 'json', success: function (result) { if(result.status){ location.href = '/index/'; }else{ $.each(result.message, function (k,v) { console.log(k,v[0].message); // <span class="error-msg">错误信息</span> var tag = document.createElement('span'); tag.className = 'error-msg'; tag.innerText = v[0].message; // input[name="user"] $('input[name="' + k + '"]').after(tag); }) } }, error: function () { } }) } </script> </body> </html>
生成HTML标签
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <style> .error-msg{ color: red; } </style> </head> <body> <form action="/login/" method="POST"> <div> <div> {{ obj1.user }} {% if obj1.errors.user %} <span class="error-msg">{{ obj1.errors.user.0 }}</span> {% endif %} </div> <div> {{ obj1.pwd }} <span class="error-msg">{{ obj1.errors.pwd.0 }}</span> </div> <div> {{ obj1.num }} <span class="error-msg">{{ obj1.errors.num.0 }}</span> </div> <div> {{ obj1.phone }} <span class="error-msg">{{ obj1.errors.phone.0 }}</span> </div> <div> {{ obj1.test }} <span class="error-msg">{{ obj1.errors.test.0 }}</span> </div> <input type="submit" value="提交" /> </div> </form> </body> </html>
2、CSRF
-,内兜,外兜
Form提交
Ajax提交
3、cookie
---保存在客户端浏览器上的
def set_cookie(self, key, value='', max_age=None, expires=None, path='/',
domain=None, secure=False, httponly=False):
不能进行跨域名--根据域名严格隔离
obj.set_cookie('k3','v3',path='/') --path='/' -- 全局缓存,所有都会网页都会生效
path='/cookie/' -- 到cookie页面可以生效,其他不生效
secure之后https
不能完全安全
def cookie(request):
print(request.COOKIES)
obj = render(request, 'cookie.html')
obj.set_cookie('k3','v3',path='/cookie/')
return obj
def cookie1(request):
print(request.COOKIES)
obj = render(request, 'cookie.html')
return obj
4、session
---保存在服务器端(内存,数据库,缓存)
失效日期默认2周
客户访问网站 session 产生一个随机字符串发回给cookie。session存在一个随机字符串,还有表示islogin=true(以及用户名密码)
下次再来访问cookie带有这个随机字符串,session一匹配成功就可以获取用户名密码,不用再进行输入了。
USER_LIST = ['alex','eric','wangminglong', 'hu'] def session_login(request): if request.method == 'POST': u = request.POST.get('user') p = request.POST.get('pwd') if p == '123' and u in USER_LIST: request.session['user'] = u return redirect('/session_index/') return render(request,'session_login.html') """ def session_index(request): user = request.session.get('user',None) if not user: return redirect('/session_login/') else: return render(request,'session_index.html',{'user': user}) """ def auth(func): def inner(request, *args,**kwargs): # print(request,args,kwargs) user = request.session.get('user', None) if not user: return redirect('/session_login/') return func(request, *args,**kwargs) return inner @auth def session_index(request): user = request.session.get('user', None) return render(request,'session_index.html',{'user': user}) @auth def session_logout(request): del request.session['user'] return redirect('/session_login/')
5、model操作补充
a. 基本操作
b. 进阶
c. 双下滑线
__ 大小于操作
__ 可以跨表
class UserInfo(models.Model):
user = models.CharField(max_length=32)
pwd = models.CharField(max_length=32)
queryset = UserInfo.objects.all()
print(queryset.query) -- SQL语句
【UserInfo对象,UserInfo对象,UserInfo对象,】
queryset = UserInfo.objects.all().values('user')
【{‘user’: 'alex'},{‘user’: 'eirc'}】
queryset = UserInfo.objects.all().value_list('user')
【('alex'),('eirc')】
=======================
一对多
class UserType(models.Model):
catption = models.CharField(max_length=32)
# 超级管理员,普通用户,游客,黑河
class UserInfo(models.Model):
user = models.CharField(max_length=32)
pwd = models.CharField(max_length=32)
user_type = models.ForignKey('UserType')
# user_type_id
# 创建UserInfo
1、 UserInfo.objects.create(user='alex',pwd='123',user_type=UserType.objects.get(id=2))
2、 UserInfo.objects.create(user='alex',pwd='123',user_type_id=2)
# 查询:
UserInfo.objects.filter(user='alex')
1、查询所有用户类型等于 普通用户 的所有用户名和密码
uid = UserType.objects.get(caption='普通用户').id
UserInfo.objects.filter(user_type_id=uid)
querset = UserInfo.objects.filter(user_type__caption='普通用户')
querset = UserInfo.objects.filter(user_type__id__gt=2)
【UserInfo对象,UserInfo对象,UserInfo对象,】
row = querset[0]
row.user
row.pwd
row.user_type.id
row.user_type.caption
###### objects __
###### row.外键字段.外键表的字段
querset = UserInfo.objects.filter(user_type__caption='普通用户').values('user','user_type__caption')
【{'user': 'alex','user_type__caption': '普通用户'},{'user': 'eric','user_type__caption': '普通用户'},】
row = querset[0]
row['user']
row['user_type__caption']
2、三张表跨表操作
class Somthing(models.Model):
name = models.CharField(max_length=32)
class UserType(models.Model):
catption = models.CharField(max_length=32)
s = models.ForignKey('Somthing')
# 超级管理员,普通用户,游客,黑河
class UserInfo(models.Model):
user = models.CharField(max_length=32)
pwd = models.CharField(max_length=32)
user_type = models.ForignKey('UserType')
UserInfo.objects.filter(user_type__s__name='xx')
===========================================================
多对多
1、创建表
2、操作
_set
作业:
用户认证Session
{% if 登录陈功 %}
<h1>{{user}}</h1>
{% ekse %}
<a ></a>
<a></a>
{% end %}