• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Django命名URL和反向解析URL实现解析

python 搞代码 4年前 (2022-01-07) 20次浏览 已收录 0个评论

这篇文章主要介绍了Django命名URL和反向解析URL实现解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

命名 URL:

test.html:

   <title>测试页面</title> <p>测试页面</p> json 数据

urls.py:

 from django.conf.urls import url from app01 import views urlpatterns = [ url(r'^test/', views.test), url(r'^json_test/', views.json_test), ]

如果 urls.py 中的 json_test/ 路径发生改变,test.html 中的地址也要改

可以使用反向 url 解析,给 json_test/ 起一个别名

urls.py:

 from django.conf.urls import url from app01 import views urlpatterns = [ url(r'^test/', views.test), url(r'^json_test/', views.json_test, name="json"), # 给该 url 匹配命名为 json ]

test.html:

   <mark style="color:transparent">来源gaodaimacom搞#代%码网</mark><title>测试页面</title> <p>测试页面</p> json 数据

这时候如果修改 urls.py 中的 json_test/ 路径,就不需要再去修改 test.html

反向解析 URL:

如果需要重定向这样的路径的话,可以在 views.py 中这样写:

 from django.shortcuts import render, redirect from django.urls import reverse # json 测试 def json_test(request): hobby = ["Music", "Movie", "Basketball", "Reading"] from django.http import HttpResponse, JsonResponse return JsonResponse(hobby, safe=False) def test(request): return redirect(reverse("json")) # 通过 json 反向得到路径 json_test/

访问:http://127.0.0.1:8000/test/ 就变成访问:http://127.0.0.1:8000/json_test/

如果 url 需要传参数的话:

urls.py:

 from django.conf.urls import url from app01 import views urlpatterns = [ url(r'^test/', views.test), url(r'^json_test/(?P[0-9]{2,4})/(?P<title>[a-zA-Z]+)/', views.json_test, name="json"), ]

test.html:

   <title>测试页面</title> <p>测试页面</p> json 数据

访问:http://127.0.0.1:8000/test/

点击 “json 数据”

反向解析需要参数的话:

urls.py:

 from django.conf.urls import url, include from app01 import views urlpatterns = [ url(r'^test/', views.test), url(r'^json_test/(?P[0-9]{2,4})/(?P<title>[a-zA-Z]+)/', views.json_test, name="json"), ]

views.py:

 from django.shortcuts import HttpResponse, redirect from django.urls import reverse def json_test(request, id, title): print("id: ", id) print("title: ", title) return HttpResponse(id+"----"+title) def test(request): return redirect(reverse("json", kwargs={"id": 23, "title": "aaaa"}))

访问:http://127.0.0.1:8000/test/

跳转到了:http://127.0.0.1:8000/json_test/23/aaaa/

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持gaodaima搞代码网

以上就是Django命名URL和反向解析URL实现解析的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Django命名URL和反向解析URL实现解析

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址