【发布时间】: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