9、 Django-重定向-Redirect

导入模块

from django.shortcuts import redirect, reverse

 

概念:在视图函数中做跳转到其它页面

 

如:

1、views.py
---------------------------------------------------------------------------------
from django.shortcuts import render
from App_route.models import *
from django.http import HttpResponse
from django.shortcuts import redirect, reverse


# 重定向
#当访问到这个函数直接跳转到百度
def my_redirect(request):
    return redirect('https://www.baidu.com')
---------------------------------------------------------------------------------

2、子路由:urls.py
--------------------------------------------------------------------------
from django.urls import path
from App_route.views import *

urlpatterns = [
    #重定向路由
    path('mydirect/', my_redirect, name='mydirect')

]
-----------------------------------------------------------------------------

3、根路由:urls.py
-------------------------------------------------------------------------
from django.contrib import admin
from django.urls import path
from App_route.views import *       #导入视图函数
from django.urls import include     #导入子路由模块 include函数


urlpatterns = [

    #直接使用根路由
    #path('user/', UserInfoView),

    #使用子路由 include 包含子路由 urls.py的路径
    #path('user/', include('App_route.urls')),

    #使用子路由:include函数  、再使用命名空间namespace
    #在使用命名空间namespace的时候:命名空间名一般和应用名相同
    #path('user/', include(('子路由urls.py的路径','App名'), namespace='App名')),
    path('user/', include(('App_route.urls', 'App_route'), namespace='App_route')),

    path('admin/', admin.site.urls),
]
________________________________________________________________________________________________

 

 

 

或跳转到本地连接

# 重定向
def my_redirect(request):
    # return redirect('https://www.baidu.com')
    #或直接跳转到本地的连接
    #跳转到用户列表
    # return redirect('/user/userlist/')

    #如果跳转到带参数的情况、跳转到id为2的用户信息界面
    # return redirect('/user/userdetail/2/')

    #使用反向解析跳转 带命名空间
    #reverse('命名空间:子路由中path的name', args=(1,))  args=(1,) 将参数1传入到路由中(以元组形式)
    # return redirect(reverse('App_route:userdetail', args=(1,)))     #位置参数传参

    #将关键字uid 为2 的值传递给 子路由名为 name=userdetail 的路由中、注意子路由中的参数名和这里的关键字 uid要一致
    return redirect(reverse('App_route:userdetail', kwargs={'uid': 2}))     #关键字传参

    #如果根路由中没有命名空间的话这里可以不写命名空间
    #return redirect(reverse('userdetail', kwargs={'uid': 2}))  # 关键字传参

    #注意如何根路由中的某个应用的路由使用了命名空间的话、后面的调用路由的地方都必须带上命名空间(如:反向解析、视图函数、和templates模板中的文件等)

 

Django路由的反向解析可以让我们在代码中是使用路由的别名替代URL路径、在修改url时避免代码中的硬编码的依赖、同时提高可读性和可维护性

#在视图函数中、反向解析URL
from django.shortcuts import render, redirect, reverse

def buy(request):
    return redirect(reverse('index'))
    return redirect(reverse('detail', args=(1,)))    #传一个参数
    return redirect(reverse('detail', kwargs={"id": 2}))


#templates中、使用别名
{% url 'detail' stu.id %}


#使用命名空间、指定命令空间后、使用反向解析时需要加上命名空间、如:
    #1、在视图函数中:
        return redirect(reverse('App: index'))
    #2、在templates中:
        {% url 'App:index' %}

 

posted @ 2024-07-01 22:32  little小新  阅读(2)  评论(0编辑  收藏  举报