【问题标题】:Django form action attribute is not working propelyDjango 表单操作属性无法正常工作
【发布时间】:2019-05-13 23:52:35
【问题描述】:

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

在 base.html 和 url 127.0.0.1:8000 下 - 我有要搜索的表格,我想把这个表格保留在这里。另一方面,我有带有视图、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 %}

【问题讨论】:

  • 您的method="post",但您获得了request.GET 参数。要么创建method="get",要么更改为request.POST

标签: python django forms elasticsearch search


【解决方案1】:

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

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

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

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

<form action="{% url 'search:search' %}" method="get">
    {% 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>

【讨论】:

  • 非常感谢它正在工作。你能给我一个提示,如何实现查询字符串,更好地链接,分享吗?
  • @user10605113:这里我们正在使用查询字符串。如果您想使用发布请求,在您看来,您应该将request.GET.get(..) 替换为request.POST.get(..)
猜你喜欢
  • 1970-01-01
  • 2013-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-11
  • 1970-01-01
  • 2010-11-07
相关资源
最近更新 更多