AI写作智能体 自主规划任务,支持联网查询和网页读取,多模态高效创作各类分析报告、商业计划、营销方案、教学内容等。 广告
使用 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