时间:2020-10-02 10:19:13 | 栏目:Python代码 | 点击:次
解决path中带参数的路径。
reverse(viewname,urlconf=None,args=None,Kwargs=None,current_app=None)
book/views.py
from django.http import HttpResponse from django.shortcuts import render,redirect,reverse # Create your views here. def index(request): username = request.GET.get("username") if username is not None: return HttpResponse("welcome!") else: return redirect(reverse('loose',kwargs={'a':100,'b':200})) def error(request,a,b): sum=a+b return HttpResponse("<h1>sum:{}</h1>".format(sum))
book/urls.py
from django.urls import path from . import views urlpatterns = [ path('', views.index,name='index'), path('error/<int:a>/<int:b>', views.error,name='loose'), ]
大体过程:启动服务器后会调用views中index函数,由于没有username参数,会重定向到loose(views.error的命名空间),即会调用error函数,此时有两个参数a,b,需要通过reverse才能够传下去。