How django Redirects Views
- 2021-07-26 08:11:53
- OfStack
When we request access to a view, we want it to be redirected to another page. What should we do?
1.HttpResponseRedirect
Requirements: Skip to 127.0. 0.1/user/index when we visit 127.0. 0.1/my_redirect
Note: To register the corresponding url
def my_redirect(request):
return HttpResponseRedirect('/user/index')
2.redirect
Requirements: Same as above
def my_redirect(request):
return redirect('/user/index')
3. reversr function dynamically generates url address to solve the problem of troublesome hard coding maintenance (less used)
If you write view functions, a lot of them are redirected to 127.0. 0.1/user/index.
Then when you want to change its redirect address, let it redirect to 127.0. 0.1/user/abc. It is necessary to modify 1 view function. Is it particularly troublesome to maintain it like this? The reverse function automatically generates the url address to solve this problem.
(1) When we set url in the project's urls. py file and the application's urls. py file.
urls. py in the project:
url(r'^user/',include("user.urls",namespace="user")),
url(r'^my_redirect',views.my_redirect)
Applied urls. py:
url(r'^index$',views.index,name="index")
Views:
# Redirect
def my_redirect(request):
url=reverse("user:index") # Write first namespace The value of, and then write name Value of !
return redirect(url)
The current situation is to access 127.0. 0.1/my_redirect and redirect directly to 127.0. 0.1/user/index.
If you want to redirect to 127.0. 0.1/user/abc, modify the applied urls.py directly to:
url(r'^abc$',views.my_redirect,name="index")
If you want to redirect to 127.0. 0.1/abc/index, modify the project's urls.py directly to:
url(r'^abc/',include("user.urls",namespace="user"))
(2) When we only set url on the project's urls. py.
urls. py in the project:
url(r'^index',views.index,name="index"),
url(r'^my_redirect$',views.my_redirect)
Views:
# Redirect
def my_redirect(request):
url=reverse("index")
return redirect(url)
The situation now is to automatically jump to 127.0. 0.1/index when accessing 127.0. 0.1/my_redirect.
If you want to redirect to 127.0. 0.1/abc, modify the urls. py file in your project directly to:
url(r'^abc',views.index,name="index")