1. 为什么使用反向解析
避免硬编码URL
2. 示例
URL: http://www.xxx.com/article/2019/
2.1. 设置路由
# app/urls.py
app_name = 'example'
#...
path('article/<int:year>/', views.articles, name='articles')
#...
2.2. 模板中使用
<!-- app/templates/appname/index.html -->
<a href="{% url 'example:articles' 2019 %}">2019 Articles</a>
2.3. 视图中使用
# app/views.py
from django.http import HttpResponseRedirect # 跳转
from django.urls import reverse # 反向解析
def redirect_to_article(request):
year = 2019
return HttpResponseRedirect(reverse('example:articles', args=(year,)))
# 或者
return HttpResponseRedirect(reverse('example:articles', args=[year]))