【发布时间】:2015-01-15 17:03:34
【问题描述】:
我在我的 django (1.7) 网站中使用 haystack (2.1.1) 和 whoosh。我很高兴,因为它正在工作,但并不完全。该应用程序显示正确的搜索,但是当我单击结果时,它不会转到产品页面。看起来我没有配置使 {{ result.object.get_absolute_url }} 无法正常工作的东西。我希望你们中的任何人都可以帮助我(作为参考我把所有的代码)
这是我的应用模型(产品/模型)
from django.db import models
class Products(models.Model):
name = models.CharField(max_length=120)
description = models.TextField()
image1 = models.ImageField(upload_to='product_images', blank=True, null=True)
price = models.FloatField(default=0.00)
slug = models.CharField(max_length=50, blank=False, null=True)
pub_date = models.DateTimeField()
def __unicode__(self):
return str(self.name)
class Meta:
ordering =['-id']
verbose_name = ('Product')
verbose_name_plural = ('Products')
这是我的 search_indexes.py,我放在我的应用程序的同一文件夹中 (products/search_indexes.py)
import datetime
from haystack import indexes
from products.models import Products
class ProductsIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
name = indexes.CharField(model_attr='name')
description = indexes.CharField(model_attr='description')
pub_date = indexes.DateTimeField(model_attr='pub_date')
def get_model(self):
return Products
def index_queryset(self, using=None):
return self.get_model().objects.filter(pub_date__lte=datetime.datetime.now())
我在设置文件中做了更改
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',
'PATH': os.path.join(os.path.dirname(__file__), 'whoosh_index'),
},
}
在我的模板文件夹“templates/search/indexes/products/products_text.txt”中创建文件
{{ object.name }}
{{ object.description }}
HTML 和 urls 与 haystack 网站中的相同(只需将 result.object.title 更改为 result.object.name)。在 URLS 中:(r'^search/', include('haystack.urls')) 和 html (templates/search/search.html)
{% extends 'base.html' %}
{% block content %}
<h2>Search</h2>
<form method="get" action=".">
<table>
{{ form.as_table }}
<tr>
<td> </td>
<td>
<input type="submit" value="Search">
</td>
</tr>
</table>
{% if query %}
<h3>Results</h3>
{% for result in page.object_list %}
<p>
<a href="{{ result.object.get_absolute_url }}">{{ result.object.name }}</a>
</p>
{% empty %}
<p>No results found.</p>
{% endfor %}
{% if page.has_previous or page.has_next %}
<div>
{% if page.has_previous %}<a href="?q={{ query }}&page={{ page.previous_page_number }}">{% endif %}« Previous{% if page.has_previous %}</a>{% endif %}
{% if page.has_next %}<a href="?q={{ query }}&page={{ page.next_page_number }}">{% endif %}Next »{% if page.has_next %}</a>{% endif %}
</div>
{% endif %}
{% else %}
{# Show some example queries to run, maybe query syntax, something else? #}
{% endif %}
</form>
{% endblock %}
正如我之前所说,它会搜索并显示它。但我不知道为什么 {{ result.object.get_absolute_url }} 不起作用,所以它显示了产品标题但没有将它们链接到他们的页面。
【问题讨论】:
-
您需要向我们展示生成该模板的
view。上下文模板中的object是什么? -
你检查你的 URLconf 了吗?当您添加 haystack 的 url 时,也许您覆盖了 Product 视图的模式,使用
urlpatterns = patterns(...)而不是urlpatterns += patterns(...)。注意=和+=之间的区别。
标签: django python-2.7 django-haystack whoosh