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

标签 python django forms elasticsearch search

我正在开发 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>

关于python - Django 表单操作属性无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53750421/

相关文章:

python - 我的套接字模块出现无效语法错误

具有多个类和 Tkinter 的 Python 属性错误

Heroku 上的 Django + MongoDB

django - 在 Django Rest Framework 中包含位置 header

python mysql配置问题

javascript - 图像而不是单选按钮/文本?

Python3错误: AttributeError: module 'urllib' has no attribute 'request'

python - 执行时和使用奇点构建镜像时的 python 版本不同,相同的官方 python docker 镜像

python - 如何从选择菜单获取数据到后端/服务器

javascript - 出现错误时添加 CSS