使用 URL 的反向解析,防止代码中引用 URL 时出现硬编码。
- 模板中:`url` 模板标记
- Python 中(视图、模型等其他代码):`reverse()` 函数
- 更高级应用:模型中定义 `get_absolute_url()` 方法
模板标记 - url
---------------
URLconf 如下:
~~~
from django.urls import path
from . import views
urlpatterns = [
#...
path('articles/<int:year>/', views.year_archive, name='news-year-archive'),
#...
]
~~~
模板中:
~~~
# 代入单个变量,如:cur_year = 2012
<a href="{% url 'news-year-archive' cur_year %}">今年 Archive</a>
# 循环展示
<ul>
{% for yearvar in year_list %}
<li>
<a href="{% url 'news-year-archive' yearvar %}">{{ yearvar }} Archive</a>
</li>
{% endfor %}
</ul>
~~~
Python 中
-----------
`django.http.HttpResponseRedirect`
`django.urls.reverse`
~~~
from django.http import HttpResponseRedirect
from django.urls import reverse
def redirect_to_year(request):
# ...
year = 2006
# ...
return HttpResponseRedirect(reverse('news-year-archive', args=(year,)))
~~~
get_absolute_url()
--------
详见:@todo
- 开始
- 安装 django
- 配置语言、时区
- 创建项目
- 执行项目
- Applications
- 应用
- 配置应用
- INSTALLED_APPS
- django apps 包
- AppConfig 子类
- 应用的复用
- 路由
- URLconf
- path
- 转换器
- re_path
- 捕获参数
- URL 反向解析
- include
- 额外参数
- URL 命名空间
- Settings
- Core Settings
- INSTALLED_APPS
- django API
- apps
- config.py -- AppConfig 类
- registry.py -- Apps 类
- db
- models.fields 包
- 字段类型
- 字段选项
- null、blank
- 模型
- 简介
- 字段
