Redirect
Redirect divided into permanent and temporary redirection redirection, reflected on the page is the browser will automatically jump from one page to another page, such as the user needs permission to access a page, but the user is not currently such powers, two faces will automatically jump to the page corresponding to the user can be given permission.
(2) Temporary Redirect: http status code is 302, showing the temporary jump page. Such as access to know almost home, visit zhihu.com, it will default to jump to signup (registration) page, will return home after only Login or Register. This way is a temporary redirect, then logged on again to access zhihu.com can access the home page.
In Django, the redirection state code 302, using the redirection redirect (to, * args, premanent = False, ** kwargs) to achieve. to be a url, whether this is representative of the permanent redirect is a permanent redirect, the default is False. About the use of redirection. Sample code is as follows:
from django.shortcuts import render, redirect, reverse
from django.http import HttpResponse
def index(request):
# 如果没有在url中传递一个参数,就相当于没有注册或者是登录,就返回注册页面
# 得到url中传递的参数,这种请求方式为GET请求
username = request.GET.get('username')
if username:
return HttpResponse('index')
else:
# 将重定向的url名传入reverse()函数进行反转,就可以得到重定向的页面的url
return redirect(reverse('signup'))
def signup(request):
return HttpResponse('signup')
In the book app urls.py file, the following sample code
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('signup/', views.signup, name='signup'),
]
In the project file urls.py relations with the sub-main url url is:
from django.urls import path, include
urlpatterns = [
path('book/', include('book.urls')),
]
Enter in the browser url: 127.0.0.1: 3000 / book /, will be redirected to 127.0.0.1:3000/book/signup/,
View detailed book / information, we can see the status code is 302, the input url: 127.0.0.1: 3000 / book / will be temporarily redirected to 127.0.0.1:3000/book/signup/.
Note that: If you enter in your browser: 127.0.0.1: 3000 / book, not back "/", there will be 301 moved permantly, is a permanent redirect to 127.0.0.1:3000/book/ .