1. 为什么使用反向解析

避免硬编码URL

2. 示例

URL: http://www.xxx.com/article/2019/

2.1. 设置路由

  1. # app/urls.py
  2. app_name = 'example'
  3. #...
  4. path('article/<int:year>/', views.articles, name='articles')
  5. #...

2.2. 模板中使用

  1. <!-- app/templates/appname/index.html -->
  2. <a href="{% url 'example:articles' 2019 %}">2019 Articles</a>

2.3. 视图中使用

  1. # app/views.py
  2. from django.http import HttpResponseRedirect # 跳转
  3. from django.urls import reverse # 反向解析
  4. def redirect_to_article(request):
  5. year = 2019
  6. return HttpResponseRedirect(reverse('example:articles', args=(year,)))
  7. # 或者
  8. return HttpResponseRedirect(reverse('example:articles', args=[year]))