Django视图重定向

视图重定向 :
  视图函数由于某些原因不再使用,请求该视图函数会被重定向到新的视图函数
会用到的页面:
redirect.html
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>在页面重定向</title>
</head>
<body>
    <h1>注册成功,<span id='redirect'>5</span>秒后自动跳转,或单击<a href="{% url 'welcomepath' %}">跳转</a></h1>
    <script type="text/javascript">
        var i = 5;
        setInterval(function(){
            i--;
            show_second = document.getElementById('redirect');
            show_second.innerHTML = i;
            if(i==0){
                location.href='{% url "welcomepath" %}';
            }
        }, 1000)
    </script>
</body>
</html>

用于redirect.html页面里跳转到的welcome.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>欢迎光临</title>
</head>
<body>
    <h1>欢迎光临</h1>
</body>
</html>

根路由

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('app/', include('myapp.urls')),
]

子路由

from django.urls import path, re_path
from . import views

urlpatterns = [
    #================视图重定向==============
    path('throwpath/', views.throw_path, name='throwpath'),
    path('newpath/', views.new_path, name='newpath'),
    path('welcomepath', views.welcome, name='welcomepath'),
]

视图 views.py

from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.urls import reverse
from . import models

def throw_path(request):
    # 该视图函数由于某些原因不再使用,请求该视图函数会被重定向到新的视图函数
    # return HttpResponse('<script>location.href="' + reverse('newpath') + '"</script>')
    return redirect(reverse('newpath'))

def new_path(request):
    return render(request, 'redirect.html')

def welcome(request):
    return render(request, 'welcome.html')


原文地址:https://www.cnblogs.com/glz666/p/13764932.html