1.前后台分离数据交换
跨域:主机,端口,协议不同
文件上传下载
file=$('.file')[0].files[i] form_data = new FormData().append('file',file)
后台采用FileResponse返回文件数据,规定响应头,通过接口调用浏览器下载工具下载文件
2.cookie组件
添加:response.set_cookie(key,value,max_age)
获取:response.COOKIES.get(key)
删除:response.delete_cookie(key)
3.session组件
添加:request.session[key]=value
形成随机字符串作为主键,session表添加字段,设置cookie
获取:request.session.get(key)
删除:request.session.flush()
Auth组件
Django为开发者提供了一套可以完成用户注册,登录,登录校验,登录信息保存,密码的密文存储等一系列功能的模块,该模板默认关联着auth_user表操作用户信息,django_session表操作session信息,
方便快捷的帮助开发者完成登录相关的认证交互功能
auth_user表常用操作
from dajngo.contrib.auth.models import User
1.创建普通用户
User.objects.create_user(username='sb',password='123')
2.创建超级用户
User.objects.create_superuser(username='root',password='root',email='1234.com')
3.获取第一个用户
user = User.objects.first()
4.修改密码
user.set_password('000')
user.save()
5.校验密码
res = user.check_password('00')
Auth组件常用功能
1.校验用户账号及密码,校验成功返回user对象
from django.contrib.auth import authenticate
user = authenticate(username=usr,password=pwd)
2.注册用户到request对象中,注册成功可以request.user访问当前登录用户(会形成session记录)
from django.contrib.auth import login
login(request,user) #注册authenticate成功(当前登录)的用户
3.注销当前注册的user(用户注销)
from django.contrib.auth import logout
logout(request)
4.校验用户登录状态
视图函数中使用
if request.user.is_authenticated():pass
模板语言中使用
{% if request.user.is_authenticated %}
{% else %}
{% endif %}
5.校验登录状态的装饰器
from django.contrib.auth.decorators import login_required
@login_required(login_url = '/user_login/')
def user_home(request):
return render(request,'user.html',locals())
扩展User表
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
#增加自定义字段
info = models.TextField(null=True)
#settings.py配置
AUTH_USER_MODEL = 'app.User'
Forms组件
1.校验表单字段
2.渲染表单字段
#表单字段的校验
<form action="" method="post" novalidate>
<input type="text" name="usr">
<input type="password" name="pwd">
<input type="email" name="email">
<input type="submit" value="注册">
</form>
#views.py核心代码
from django.shortcuts import render,HttpResponse
from django import forms
#自定义校验表单字段的类,继承forms.Form,并用forms下具体字段完成校验
class CheckForm(form.Form):
通过error_messages自定义错误信息
usr = forms.CharField(min_length=3,max_length=10,error_messages={'min_length':'长度至少为三'})
pwd = forms.CharFeild(min_length=3,max_length=10)
email=froms.EmailField(error_messages={'invalid':'邮箱不合法','required':'必填项'})
def regiater(request):
if request.method == 'GET':
return render(request,'register.html')
if request.method == 'POST':
#校验请求的所有数据
check_form = CheckForm(request.POST)
if check_form.is_valid():
#查看校验成功的数据为字典类型
print(check_form.cleaned_data)
return HttpResponse('注册成功')
else:
#查看校验失败的数据,为封装的字典类型
print(check_form.errors)
return HttpResponse('注册失败')
表单元素的渲染
python
#view.py 改动代码
class CheckForm(forms.Form):
usr = forms.CharField(min_length=3,max_length=10,label='用户名')
pwd = forms.CharField(min_length=3,max_length=10,label='密码')
email = forms.EmailField(label='邮箱')
def register(request):
if request.method == 'GET':
check_form =CheckForm()
return render9request,'register.html',{'check_form':check_form})
html
register.html核心代码
方式一
<form action="" method="post">
{{check_form.usr}}
{{check_form.pwd}}
{{check_form.email}}
<input type="submit" value="注册">
</form>
方式二
<form action="" method="post">
{% for ele in check_form %}
{{ele}}
{% endfor %}
<input type="sumit" value="注册">
</form>
方式三
<from action="" method="post">
<table>{{check_form.as_table}}</table>
<input type="submit" value="注册"></from>
方式四
<form action="" method="post">
<ul> {{check_form.as_ul}}</ul>
<input type="submit" value="注册">
</form>
方式五
<form action="" method ="post">
{{check_form.as_p}}
<input type="submit" value="注册">
</form>
错误信息的渲染
python
views.py
class CheckForm(forms.Form):
usr=forms.CharField(
min_length=3,
max_length=10,error_messages={
'min_length':'长度至少3',
'max_length':'长度最多为10,'required':'必填项'},
label='用户名')
pwd=forms.CharField(
min_length=3,max_length=10,error_messages={
'min_length':'长度至少为3',
'max_length':'长度至少为10','required':'必填项'},label='密码')
eamil = forms.EmailField(
error_messages={
'invalid':'邮箱不合法',
'required':'必填项'})
def register(request):
if request.method =='GET:
check_form = CheckForm()
if request.method == 'POST':
check_form = CheckForm(request.POST)
if check_form.is_valid():
return HttpResponse('注册成功')
return render(request,'register.html',locals())
html
<form action="" method="post" novalidate>
{% for ele in check_form %}
<p>
{{ ele.label }}:{{ele}}
<span style="color;red">{{ ele.errors.0}}</span>
</p>
{% endfor %}
<input type="submit" value='注册'>
</form>
局部钩子验证
python
在自定义验证类CheckForm中添加局部验证钩子
class CheckForm(forms.Form):
def clean_usr(self):
name = self.cleaned-data.get('usr')
import re
if re.match('^[0-9]',name):
from django.core.exceptions import ValidationError
raise ValidationError('不能以数字开头')
return name
全局钩子验证
python
views.py
class CheckForm(forms.Form):
usr = forms.CharField(
min_length=3,
max_length=10,
error_messages={
'min_length':'长度至少为3',
'max_length':'长度最多为10',
'required':'必填项'},
label='用户名',
widget=forms.TextInput(attr={'placeholder':'请输入用户名'}))
pwd=forms.CharField(
min_length=3,
max_length=10,
error_messages={
'min_length':'长度至少为3',
'max_length':'长度最多为10',
'required':'必填项'},
label='密码',
widget=forms.Passwordinput(attr={'placeholder':'请输入密码'}))
re_pwd = forms.CharField(
min_length=3,
max_length =10,
error_messages={
'min_length':'长度至少3',
'max_length':'长度最多为10',
'required':'必填项'},
label='确认密码',
widget=forms.PasswordInput(attr={'placeholder':'请确认密码'}))
def clean(self):
pwd=self.cleaned_data.get('pwd')
re_pwd=self.cleaned_data.get('re_pwd')
if pwd == re_pwd:
return self.cleaned_data
from django.core.exceptions import ValidationError
raise ValidationError('两次密码不一致')
def register(request):
if request.method == 'GET':
check_form = CheckForm()
if request.method == 'POST':
check_form = CheckForm(request.POST)
if check_form.is_valid():
return HttpResponse('注册成功')
else:
#拿到全局钩子抛出的错误信息
all_error = check_form.errors.get('__all__',None)
return render(request,'register.html',locals())
html
<form action="" method="post" novalidate>
{% for ele in check_form %}
<p>
{{ ele.label}}:{{ele}}
<span style="color:red">{{ele.errors.0}}</span>
{% if ele.label == '确认密码' %}
<span style="color:red"> {{all_error.0}}</span>
{% endif %}
</p>
{% endfor %}
<input type="submit" value="注册'>
</form>
中间件
自定义中间件
python
自定义中间件类:app.testmiddleware.py
from django.utils.deprecation import MiddlewareMixin
class MyMiddleware1(MiddlewareMixin):
def process_request(self,request):
'''请求处理
request;请求对象
return 一般没有返回值,但可以返回HttpResponse对象
def process_view(self,request,callback,callback_args,callback_kwargs):
视图函数预处理
request:请求对象
claaback:路由返回的视图函数地址
callback_args:视图函数的位置参数(元组)
callback_kwargs:视图函数的关键字参数(字典)
return :一班没有返回值,但可以返回HttpResponse对象
def process_exception(self,request,exception):
视图函数异常处理
request:请求对象
exception:视图函数的异常对象
return:一般没有返回值,但可以返回HttpResponse对象
def process_template_response(self,request,response):
视图函数返回值为拥有render方法的对象,该方法会执行
request:请求对象
response:响应对象
return :一定要返回response
return response
def process_response(self,request,response):
响应处理
request:请求对象
response:响应对象
return :一定要返回response
return response
class MyMiddleware2(MiddlewareMixin):
def process_request(self,request):
pass
使用自定义中间件
python
在settings.py中配置自定义中间件
MIDDLEWARE = [...
'app.testmiddleware.MyMiddleware1',
'app.testmiddleware.MyMiddleware2',
]
form完成csrf认证
html
<form action="" method="post">
{% csrf_token %}
</form>
...
ajax完成csrf认证
html
<script src="/static/jquey-33.1.js></script>
<script src="/static/jquery.cookie.js"></script>
<script>
token = $.cookie('csrftoken');
$.ajax({
url: '/',
type: 'post',
headers:{'X-CSRFToken': token},
data: {
msg: '请求数据'
},
success: function (data) {
console.log(data)
}
})
</script>