Python全系列 教程
3567个小节阅读:5931.1k
目录
鸿蒙应用开发
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
url调度器除了从用户发起请求,到匹配对应的view,还能在python程序中调用进行匹配,通过 path或re_path 中 的name属性进行解析
示例:
urls中配置:
xxxxxxxxxx
from django.urls import path
from . import views
urlpatterns = [
#...
path('articles/<int:year>/', views.year_archive, name='news-year-archive'),
#...
]
在模板中测试
1.views.py跳转到页面
xxxxxxxxxx
def do_html(request):
return render(request,'redirect_test.html')
def year_archive(request,year):
return HttpResponse(f'重定向成功{year}')
2.模板中代码
xxxxxxxxxx
# 模板中:
<a href="{% url 'news-year-archive' 2012 %}">2012 Archive</a>
在python代码
xxxxxxxxxx
from django.urls import reverse
from django.http import HttpResponseRedirect
def redirect_to_year(request):
# ...
year = 2006
# ...
return HttpResponseRedirect(reverse('news-year-archive', args=(year,)))
xxxxxxxxxx
"""
在模型中实现方法:
def get_absolute_url(self):
from django.urls import reverse
return reverse('news-year-archive', args=[str(self.id)])
然后在 模板 中如下使用:
"""
<a href="{{ object.get_absolute_url }}">{{ object.name }}</a>