Django中如何在表单action的URL内传递动态页面标题参数
实现方案
针对wiki场景的页面标题传参需求,推荐使用路径参数的实现方式,语义更清晰、符合URL规范,修改步骤如下:
1. 修改路由配置(urls.py)
将原固定路由改为带动态参数的动态路由,匹配页面标题字符串:
# 修改前 # path("wiki/edit/", views.edit_page, name="edit") # 修改后 path("wiki/edit/<str:page>/", views.edit_page, name="edit")
<str:page>是Django内置的路径转换器,匹配不含斜杠的任意字符串,刚好适配Markdown文件名作为页面标题的场景,会自动把匹配到的字符串传入视图的page参数。
2. 修改前端表单代码
把模板中动态生成的{{ title }}作为参数传入反向生成的编辑页URL,同时GET请求无需携带CSRF令牌,可以移除冗余代码:
<!-- 修改前 <form action="{% url 'edit' %}"> {% csrf_token %} --> <!-- 修改后 --> <form action="{% url 'edit' page=title %}"> <div class="form-group mt-4"> <button class="btn btn-outline-info" type="submit">Edit page</button> </div> </form>
- Django的
{% url %}模板标签会自动处理title中的空格、特殊字符、中文等内容的URL编码,不需要手动转义。
3. 完善视图异常处理
现有视图的参数已经和路由传参逻辑对应,仅需补充文件不存在的异常判断,避免读取空文件报错:
def edit_page(request, page): if request.method == "GET": entry_content = util.get_entry(page) # 对应Markdown文件不存在时直接返回404 if not entry_content: from django.http import Http404 raise Http404("编辑页面不存在") return render(request,"encyclopedia/edit_page.html", { "pagename": page, "html": markdown2.markdown(entry_content) })
备选实现方案(GET查询参数)
如果不想改动原有路由结构,也可以通过GET查询参数传递页面标题,修改逻辑如下:
- 路由保持原有配置无需改动:
path("wiki/edit/", views.edit_page, name="edit") - 前端表单新增隐藏域携带
{{ title }}:
<form action="{% url 'edit' %}"> <input type="hidden" name="page" value="{{ title }}"> <div class="form-group mt-4"> <button class="btn btn-outline-info" type="submit">Edit page</button> </div> </form>
- 调整视图从请求中读取参数:
def edit_page(request): if request.method == "GET": page = request.GET.get("page") entry_content = util.get_entry(page) if page else None if not entry_content: from django.http import Http404 raise Http404("编辑页面不存在") return render(request,"encyclopedia/edit_page.html", { "pagename": page, "html": markdown2.markdown(entry_content) })
注意事项
- 如果你的页面标题包含斜杠(比如采用「分类/页面名」的结构),可以把路由中的
<str:page>替换为<path:page>,支持匹配带斜杠的路径。 - 后续提交编辑内容(POST请求)时,再把
{% csrf_token %}加回表单即可。
内容的提问来源于stack exchange,提问作者blur
相关产品推荐
相关产品推荐

