重定向的三种方式
HttpResponseRedirect
urls部分
path('index3/', views.index3_view),
path('show_all2/', views.show_all2_view),
views部分
def index3_view(request):
return HttpResponseRedirect('/stu/show_all2')
def show_all2_view(request):
return HttpResponse('hello')
其实这个重定向之前遇到过,在从views到urls的逆向传参的时候用过。
这里也是先访问index3,重回到url里,寻找show_all2,最终返回hello
301永久重定向
302临时重定向
默认是302,F12可以看到
redirect两类指向
全小写redirect,看源码,默认不带参数,是临时302,其实还是HttpResponseRedirect
def index3_view(request):
return redirect('/stu/show_all2/', permanent='True')
当permanent参数为True时,是永久301,即HttpResponsePermanentRedirect
def index3_view(request):
return redirect('/stu/show_all2/', permanent='True')
需要清空缓存
status_code
自定义response响应头,之前讲过的类似魔术方法__setitem__
response = HttpResponse()
response.status_code=302/301
response.setdefault('Location','/stu/show_all2/')
return response
301和302的切换需要清除缓存
感觉方法3最原始,方法1是方法3的封装,方法2是方法1和永久方法1的封装
定制错误页面
首先删掉debug,在setting.py里进行修改
DEBUG = False
#开发后改为指定域名,例如baidu.com,星号代表局域网内任何ip前缀都可以访问
ALLOWED_HOSTS = ['*']
在template里创建404和500.html页面
body里就只有这个图片,系统会自己找到该名称
<img src="https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2047903001,4087545182&fm=26&gp=0.jpg"/>
当输入一个不存在的页面时,会报404
当源码有错误时,比如写一个1/0,会报500
def show_all2_view(request):
1/0
return HttpResponse('hello')