DJANGO-URL反向解析REVERSE实例讲解

yipeiwu_com6年前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才能够传下去。

以上就是本次介绍的全部相关知识点,感谢大家的学习和对【听图阁-专注于Python设计】的支持。

相关文章

Python正则表达式完全指南

Python正则表达式完全指南

正则表达式处理文本有如疾风扫秋叶,绝大部分编程语言都内置支持正则表达式,它应用在诸如表单验证、文本提取、替换等场景。爬虫系统更是离不开正则表达式,用好正则表达式往往能收到事半功倍的效果。...

Python实现PS滤镜功能之波浪特效示例

Python实现PS滤镜功能之波浪特效示例

本文实例讲述了Python实现PS滤镜功能之波浪特效。分享给大家供大家参考,具体如下: 这里用 Python 实现 PS 滤镜的波浪特效,具体效果可以参考附录说明 import nu...

Pytorch 实现focal_loss 多类别和二分类示例

我就废话不多说了,直接上代码吧! import numpy as np import torch import torch.nn as nn import torch.nn.func...

python制作一个桌面便签软件

# 2014.10.15 更新了memo.zip, 网盘的exe:修复:1.隔日启动不能正常加载json,加入:1.隐藏任务栏图标,2.通过垃圾桶进行窗口移动。 # 2014.10.8...

Python 解码Base64 得到码流格式文本实例

我就废话不多说了,直接上代码吧! # coding:utf8 import base64 def BaseToFlow(): while True: str =...