• 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')


  • 相关阅读:
    文件上传到服务器,写入文件和读取文件
    ajax
    jquery.gritter 提示
    lambda
    C# 对象初始化器和集合初始化器
    C# HttpHelper万能框架实现 接口
    插件总结
    backbone.js之Model篇 简单总结和深入(2)
    backBone.js初识
    利用 bugly 分析应用崩溃
  • 原文地址:https://www.cnblogs.com/glz666/p/13764932.html
Copyright © 2020-2023  润新知