Url - 使用Haystack / Whoosh jquery渲染搜索结果时出现问题

时间:2015-03-29 20:44:07

标签: jquery ajax django django-haystack whoosh

我已经按照教程在Django 1.6中使用Haystack和Whoosh创建搜索查询。搜索模板有效,但在填写并提交查询时,url的自动检测会生成生成URL的404; myapp.entry,无法找到。我试过改变ajax.js中的url / article / search / to / search /但它没有帮助。有什么想法吗?

在settings.py

HAYSTACK_CONNECTIONS = {
    'default': {
        'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',
        'PATH': os.path.join( os.path.dirname(__file__), 'whoosh' ),
    },
}
在views.py中

from haystack.query import SearchQuerySet

def search_titles(request):
    #'' - defaultvalue if searchvalue (search_text) is None
    articles =SearchQuerySet().autocomplete(content_auto=request.
POST.get('search_text',''))

    return render(request,'ajax_search.html',{"articles":articles})
在urls.py中

urlpatterns = patterns('',
   url(r'^search/',include('haystack.urls')), 

)

在models.py

class Entry(models.Model):
    datetime = models.DateTimeField(auto_now_add = True)
    title = models.CharField(max_length = 70)
    content = models.TextField()
    author = models.ForeignKey(User)
    entry_count = models.PositiveIntegerField()
    n_pingbacks = models.PositiveIntegerField()

    belongsTo = models.ForeignKey(Topic)
    def __unicode__(self):
        return self.title

在search_indexes.py

from haystack import indexes
from myapp.models import Entry
import datetime

class EntryIndex(indexes.SearchIndex, indexes.Indexable):

    text = indexes.CharField(document=True,use_template=True)
    datetime = indexes.DateTimeField(model_attr='datetime')

    content_audio = indexes.EdgeNgramField(model_attr='title')

    # get the relevant model
    def get_model(self):
        return Entry

    # returning results from guideline
    def index_queryset(self, using=None):
        """used when the entire index for model is updated """

        return self.get_model().objects.all()

在ajax.js

$(function(){

    $('#search').keyup(function() {

        $.ajax({
            type: "POST",
            url: "/search/",
            data: { 
                'search_text' : $('#search').val(),
                'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()
            },
            success: searchSuccess,
            dataType: 'html'
        });

    });

});

function searchSuccess(data, textStatus, jqXHR)
{
    $('#search-results').html(data);
}

在myapp / templates / search / indexes / myapp / entry_text.txt

{{ object.title }}
{{ object.body }}

在myapp / templates / search / indexes / search.html

{% extends 'base.html' %}

{% block content %}
    <h2>Search</h2>

    <form method="get" action="../">
        <table>
            {{ form.as_table }}
            <tr>
                <td>&nbsp;</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.title }}</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 }}&amp;page={{ page.previous_page_number }}">{% endif %}&laquo; Previous{% if page.has_previous %}</a>{% endif %}
                    |
                    {% if page.has_next %}<a href="?q={{ query }}&amp;page={{ page.next_page_number }}">{% endif %}Next &raquo;{% if page.has_next %}</a>{% endif %}
                </div>
            {% endif %}
        {% else %}
            {# Show some example queries to run, maybe query syntax, something else? #}
        {% endif %}
    </form>
{% endblock %}

在myapp / templates / ajax_search.html

{% if articles.count > 0 %}

{% for article in articles %}

   <li><a href="{{article.object.get_absolute_url}}">{{article.object.title}}</a></li>

{% endfor %}

{% else %}

<li>No searchresults to display!</li>

{% endif %}

1 个答案:

答案 0 :(得分:1)

表单中的网址错误:

改变这个: <form method="get" action="../"> 通过这个:

 <form method="get" action="{% url 'haystack_search' %}">