[py]django实现url跳转

xiaoxiao2021-02-28  55

HttpResponseRedirect实现uri跳转

需求: 访问/index 跳转到 /home

1.写url

from learn import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^index/', views.index), url(r'^home/', views.home), ]

2.写views

from django.shortcuts import render,HttpResponseRedirect,HttpResponse # Create your views here. def index(request): return HttpResponseRedirect("/home") def home(request): return HttpResponse("home page")

3.测试访问

http://127.0.0.1:8000/index/ 跳转到了http://127.0.0.1:8000/home/

注: 跳转uri同时可以传参

return HttpResponseRedirect('/commons/invoice_return/index/?message=error') #跳转到index界面

另官网说

The first argument to the constructor is required – the path to redirect to. This can be a fully qualified URL (e.g.’http://www.yahoo.com/search/‘) or an absolute path with no domain (e.g. ‘/search/’)。 参数既可以使用完整的url,也可以是绝对路径。

return HttpResponseRedirect("https://www.baidu.com/") #访问http://127.0.0.1:8000/index/ 跳转到了 https://www.baidu.com/

redirect+reverse重定向

需求: 访问/index 跳转到 /home

1.写urls

from learn import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^index/', views.index), url(r'^home/', views.home,name="home"), # reverse是根据name字段解析的. ]

2,写views

from django.shortcuts import render,HttpResponseRedirect,HttpResponse from django.core.urlresolvers import reverse from django.shortcuts import redirect # Create your views here. def index(request): # return HttpResponseRedirect("/home") # return HttpResponseRedirect("https://www.baidu.com/") return redirect(reverse('home', args=[])) def home(request): return HttpResponse("home page")

可以对比下HttpResponseRedirect实现方式:

def old_add2_redirect(request, a, b): return HttpResponseRedirect( reverse('add2', args=(a, b)) )
转载请注明原文地址: https://www.6miu.com/read-52246.html

最新回复(0)