【问题标题】:django template form target with dynamic data具有动态数据的 django 模板表单目标
【发布时间】:2020-06-21 13:42:40
【问题描述】:

我是 django 模板的新手。我在标题中有一个搜索字段,我想以这种格式发送搜索到的关键字 search/q/{{keyword}}/

我的html代码是这样的

<form action="{% url 'content.search' q=searched_key %}" class="search-input">
    <input type="text" name="searched_key">
    <button type="submit"><i data-feather="search"></i></button>
</form>

我想获取输入值并发送,但结果 url 是这个
http://127.0.0.1:8000/contents/search/q//?searched_key=test
我怎样才能以正确的方式做到这一点?

【问题讨论】:

    标签: html django forms django-templates


    【解决方案1】:

    你可以POST你的搜索值作为表单(不需要在url中使用/search/q//?searched_key=test),你的视图应该是这样的:

    def search_view(request):
        if request.method == "POST":
            search_key = form.save()
            search_result = Content.objects.filter(key=search_key)
    
        context = {
            'results': search_result,
        }
        return render(request, 'content.html', context) 
    

    【讨论】:

      【解决方案2】:

      您最好使用 javascript 来完成此操作。

      <form id="form-id">
          <input type="text" id="searched_key" name="searched_key">
          <button type="submit"><i data-feather="search"></i></button>
      </form>
      
      <script type="text/javascript">
      
      function submitForm(e) {
          // Prevent default form submit
          e.preventDefault();
          // Get the search query
          let query = document.getElementById("searched_key").value;
          // redirect to the url with the query appended
          window.location.href = "/contents/search/" + query + "/";
          return false;
      }
      
      // Add an event listener to the form when the page loads
      window.addEventListener('load', function() {
          document.getElementById("form-id").addEventListener('submit', submitForm);
      });
      
      </script>
      

      【讨论】:

      • 什么不起作用?我可能误解了原来的问题
      • django 引发错误,找不到此消息参数。我对 url 进行了硬编码,并在函数末尾添加了 return false 。有效。谢谢你的帮助
      • 太棒了,我刚刚注意到我在{% url %} 中打错了,我错误地使用了下划线,这可能是找不到参数的来源。 (我已经更新了我的答案)
      • 不,我在测试前更正了。这是因为在视图中我们有一个获取参数的格式。喜欢:q=searched_key 格式类似于 /contents/search/{q}/ 我试过这个var url = "/contents/search/" + input + "/" 并使用了window.location.href = url 再次感谢
      猜你喜欢
      • 2017-03-23
      • 2019-03-15
      • 2017-03-18
      • 2017-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-11
      相关资源
      最近更新 更多