Skip to main content
 首页 » 编程设计

python之Django 表单操作属性无法正常工作

2024年12月31日19tuyile006

我正在开发 django 1.11 中的应用程序,用于搜索功能。我安装了 elasticsearch - 这里一切正常。

在 base.html 和 url 127.0.0.1:8000 下 - 我有要搜索的表格,我想将此表格保留在这里。另一方面,我有带有 View 、url、模板的搜索应用程序 - 在 url 127.0.0.1:8000/search/ 下 - 搜索在这里工作。

为了解决这个问题——在主页上搜索并在站点上重定向结果我试图在 django 表单中使用 action 属性。

base.html 中的表单

    <form action="{% url 'search:search' %}" method="post"> 
        {% csrf_token %} 
        <div class="input-group"> 
          <input type="text" class="form-control" id="q" {% if request.GET.q %}value="{{ request.GET.q }}"{% endif %} name="q" placeholder="Search"> 
          <div class="input-group-append"> 
            <button class="btn btn-outline-primary" type="button">GO</button> 
          </div> 
        </div> 
    </form> 

在搜索应用中查看

def search(request): 
    q = request.GET.get('q') 
    if q: 
        posts = PostDocument.search().query('match', title=q) 
    else: 
        posts = '' 
    return render(request, 'search/search.html', {'posts': posts}) 

带有结果的模板

{% extends 'base.html' %} 
 
{% block content %} 
    {% for p in posts %} 
        <a href="#">{{ p.title }}</a> 
    {% endfor %} 
 
{% endblock content %} 
{% block sidebar %}{% endblock sidebar %} 

请您参考如下方法:

您在这里混淆了 GET 和 POST。如果方法是 method="post",则数据会在请求中传递,因此最终会出现在 request.POST 查询字典中。

另一方面,如果方法是 method="get",则数据将在 URL 的 querystring 中结束。在那种情况下,您确实可以使用 request.GET。

通常(并非总是),搜索查询是使用查询字符串完成的,从那时起,一个人可以复制 URL 并将其发送给另一个人,该人因此可以看到搜索结果。

因此您可以将表单更改为:

<form action="{% url 'search:search' %}" method="<b>get</b>"> 
    {% csrf_token %} 
    <div class="input-group"> 
        <input type="text" class="form-control" id="q" {% if request.GET.q %}value="{{ request.GET.q }}"{% endif %} name="q" placeholder="Search"> 
        <div class="input-group-append"> 
            <button class="btn btn-outline-primary" type="button">GO</button> 
        </div> 
    </div> 
</form>