python - Django:将表单数据转换为 'clean url'

标签 python html django forms clean-urls

假设我有以下形式:

<form id="search-form" class="form-horizontal" method="GET" action="/results/" role="form">
    <input type="text" class="form-control" id="query" name="query">

    <button type="submit"  form="search-form" class="btn btn-primary">
        <span class="glyphicon glyphicon-search" aria-hidden="true"></span>       
    </button>
</form>

目前,当提交表单时,url 包含查询作为参数,如下所示:www.<my-domain>.com/results?query=<some-query> 。然而,出于搜索引擎优化的目的,我想将其转换为“干净的网址”,它看起来更像这样:www.<my-domain>.com/results/<some-query> .

我对 urls.py 进行了以下修改:

urlpatterns = [
    ...
    url(r'^results/(?P<query>[a-zA-Z ]+)$', views.ResultsView.as_view(), name="results"),
    ...
]

所以我应该能够在 ResultsView 中获取查询值,如下所示:

class ResultsView(TemplateView):

    def dispatch(self, request, *args, **kwargs):

        query = kwargs.get('query')

如何提交表单,使其与相应的 url 模式匹配?我尝试摆弄表单操作,将输入 id 传递给它,如下所示: action="/results/query/" ,但显然,它认为 query是一个文字字符串,不会将其替换为输入的值。

最佳答案

您可以使用 JQuery 轻松完成此操作。单击按钮时,阻止默认操作,并在 window.location.href 中定义应重定向到的 url。

<script>
    $(document).ready(function () {
        $("button").click(function (e) {
            e.preventDefault();
            query = $("#query").val();
            window.location.href = location.origin + "/results/" + query;
        });
    });
</script>

不要忘记添加依赖项

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js">

关于python - Django:将表单数据转换为 'clean url',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46047152/

相关文章:

html - 如何在div中将文字环绕在图像周围?

django 管理站点模型未显示

django - 如何使用 1 个 django 项目管理多个网站

python - 选项 auto_now、auto_now_add 和 default 是互斥的。可能只存在这些选项之一

python - 避免 for 循环变量切入 Python 全局命名空间的方法

python - 无法使用 python 打印列中的目录列表

javascript - Reactjs 下载没有 anchor 标记或没有在新选项卡中打开文件的文件

python - 按下按钮时 Tkinter GUI : Adding new entry boxes using . grid()

python::遍历嵌套的 JSON 结果

html - 如何禁用 HTML 中大字的表格大小调整