【发布时间】:2019-10-15 10:06:26
【问题描述】:
我按照 Mike Hibbert 的教程:https://www.youtube.com/watch?v=B-n6_m66TmA 实现了一个有效的 Django 1.6 haystack/whoosh 搜索字段。该实现在 url 'search' 的导航栏中的 twitter 引导搜索字段中工作。我想在我的应用程序的几个页面中使用该实现,但它不起作用。
我尝试在其他带有搜索栏的页面中实现 search.html 代码,但它将搜索 url 前缀从“search/...”更改为页面 url,例如到首页上的“front/...”。我还尝试将 search.html 包含在其他页面中,作为块内容和模板中的包含标记,但它没有奏效。
# in app/templates/search/indexes/search.html
{% extends 'base_searches.html' %}
{% block content %}
<form method="get" action=".">
<table>
<tr><th><label for="id_q"></label></th><td><input type="text" id="id_q"
name="q" placeholder="Search..." class="form-control" /><button
class="btn btn-success" type="submit" value="Search"><spaclass="glyphicon
glyphicon-search"></span></button></td></tr>
<tr>
<td> </td>
{% if query %}
{% for result in page.object_list %}
<div class="alert alert-success" role="alert">
Hi, {{ user }}, here's the found database match for your search
<a href="{{ result.object.get_absolute_url }}">
{{result.object.title }}.</a></div>
{% empty %}
<div class="alert alert-info" role="alert">
<strong>Hi {{ user }}, there's no match found in the
database for your search !.</strong>
</div>
{% endfor %}
{% endif %}
<div class="col-xs-6 col-sm-3 sidebar-offcanvas" id="sidebar">
<!--/.sidebar-offcanvas-->
<!--/row-->
<hr>
<td>
</td>
</tr>
</table>
</form>
</body>
</html>
{% endblock %}
# in models.py for each indexed model field
def get_absolute_url(self):
return '%s' % self.id
# in app/templates/base_searches.html
<form class="navbar-form navbar-right" id="search">{% csrf_token %}
<center><h> <td colspan="1" id="content">{% block content %}}
{% endblock %} </center></td></h>
<ul id="search-results">
</ul>
</form>
in urls.py
from haystack.query import SearchQuerySet
url(r'^search/',include('haystack.urls'),name='haystack_search'),
# in search_indexes.py
from haystack import indexes
from app.models import Article
class ArticleIndex(indexes.SearchIndex, indexes.Indexable):
text= indexes.CharField(document=True,use_template=True)
content = indexes.CharField(model_attr='description')
content_auto = indexes.EdgeNgramField(model_attr='title')
def get_model(self):
return Article
def index_queryset(self, using=None):
"""used when the entire index for model is updated """
return self.get_model().objects.all()
# in app/templates/search/indexes/appname/article_text.txt
{{ object.title }}
{{ object.content}}
我如何将 search.html 包含在其他页面中,因为我已将其包含在 base_searches.html 的导航栏中,并为搜索结果对象的 get_absolut_url 函数维护前缀 search/..searchresult 而不是我试图将其包含在其中的其他页面的 url 前缀,例如前/..搜索结果?当尝试使用 url front/ 在首页中实现它时,或者有更好的方法在多个应用程序页面的搜索字段中使用 haystack whoosh 搜索?
【问题讨论】:
标签: python django django-haystack whoosh