more integrated to templates
authorMarcin Koziej <marcin.koziej@nowoczesnapolska.org.pl>
Thu, 24 Nov 2011 11:28:33 +0000 (12:28 +0100)
committerMarcin Koziej <marcin.koziej@nowoczesnapolska.org.pl>
Thu, 24 Nov 2011 11:28:33 +0000 (12:28 +0100)
apps/catalogue/fields.py
apps/catalogue/forms.py
apps/catalogue/urls.py
apps/search/index.py
apps/search/urls.py
apps/search/views.py
wolnelektury/templates/catalogue/search_multiple_hits.html
wolnelektury/templates/newsearch/search.html

index 853a321..57ce581 100644 (file)
@@ -108,7 +108,8 @@ class JQueryAutoCompleteSearchWidget(JQueryAutoCompleteWidget):
         $('#%s')
         .autocomplete($.extend({
           minLength: 0,
-          select: autocomplete_result_handler
+          select: autocomplete_result_handler,
+          focus: function (ui, item) { return false; }
         }, %s))
         .data("autocomplete")._renderItem = autocomplete_format_item;
         """ % (field_id, options)
index 71412e1..92f50ed 100644 (file)
@@ -33,12 +33,17 @@ class SearchForm(forms.Form):
     q = JQueryAutoCompleteSearchField('/newsearch/hint/') # {'minChars': 2, 'selectFirst': True, 'cacheLength': 50, 'matchContains': "word"})
     tags = forms.CharField(widget=forms.HiddenInput, required=False)
 
+    book = forms.IntegerField(widget=forms.HiddenInput, min_value=0, required=False)
+
     def __init__(self, *args, **kwargs):
         tags = kwargs.pop('tags', [])
+        book = kwargs.pop('book', None)
         super(SearchForm, self).__init__(*args, **kwargs)
-        self.fields['q'].widget.attrs['title'] = _('title, author, theme/topic, epoch, kind, genre')
+        self.fields['q'].widget.attrs['title'] = _('title, author, theme/topic, epoch, kind, genre, phrase')
            #self.fields['q'].widget.attrs['style'] = ''
         self.fields['tags'].initial = '/'.join(tag.url_chunk for tag in Tag.get_tag_list(tags))
+        if book is not None:
+            self.fields['book'].initial = book.id
 
 
 class UserSetsForm(forms.Form):
index c770892..5d623fa 100644 (file)
@@ -20,7 +20,7 @@ urlpatterns = patterns('catalogue.views',
     url(r'^polki/nowa/$', 'new_set', name='new_set'),
     url(r'^tags/$', 'tags_starting_with', name='hint'),
     url(r'^jtags/$', 'json_tags_starting_with', name='jhint'),
-    url(r'^szukaj/$', 'search', name='search'),
+    url(r'^szukaj/$', 'search', name='old_search'),
 
     # zip
     #url(r'^zip/pdf\.zip$', 'download_zip', {'format': 'pdf', 'slug': None}, 'download_zip_pdf'),
index a3a62de..7fffb57 100644 (file)
@@ -639,10 +639,12 @@ class Hint(object):
             return None
 
     def part_filter(self):
+        fs = []
         if self.part_tags:
-            return self.tag_filter(self.part_tags, field='themes')
-        else:
-            return None
+            fs.append(self.tag_filter(self.part_tags, field='themes'))
+        if self.book is not None:
+            bf = TermsFilter()
+            bf.addTerm # TODO
 
     def should_search_for_book(self):
         return self.book is None
index 3ac5e49..607f094 100644 (file)
@@ -5,7 +5,7 @@
 from django.conf.urls.defaults import *
 
 urlpatterns = patterns('search.views',
-    url(r'^$', 'main', name='newsearch'),
+    url(r'^$', 'main', name='search'),
     url(r'^hint/$', 'hint'),
 )
 
index ff831f0..438989c 100644 (file)
@@ -4,14 +4,16 @@ from django.shortcuts import render_to_response, get_object_or_404
 from django.template import RequestContext
 from django.contrib.auth.decorators import login_required
 from django.views.decorators import cache
+from django.http import HttpResponse, HttpResponseRedirect, Http404, HttpResponsePermanentRedirect
 
 from catalogue.utils import get_random_hash
-from catalogue.models import Book, Tag, TAG_CATEGORIES
+from catalogue.models import Book, Tag, Fragment, TAG_CATEGORIES
 from catalogue.fields import dumps
 from catalogue.views import JSONResponse
 from catalogue import forms
 from search import MultiSearch, JVM, SearchResult
 from lucene import StringReader
+from suggest.forms import PublishingSuggestForm
 
 import enchant
 
@@ -105,15 +107,25 @@ def main(request):
 
     if 'q' in request.GET:
         tags = request.GET.get('tags', '')
+        query = request.GET['q']
+        book_id = request.get('book', None)
+        book = None
+        if book_id is not None:
+            book = get_object_or_404(Book, id=book_id)
+
         hint = srch.hint()
         try:
             tag_list = Tag.get_tag_list(tags)
         except:
             tag_list = []
 
+        if len(query) < 2:
+            return render_to_response('catalogue/search_too_short.html', {'tags': tag_list, 'prefix': query},
+                                      context_instance=RequestContext(request))
+
         hint.tags(tag_list)
+        hint.book(book)
 
-        query = request.GET['q']
         toks = StringReader(query)
         fuzzy = 'fuzzy' in request.GET
         if fuzzy:
@@ -127,8 +139,26 @@ def main(request):
         for r in results:
             print r.hits
 
-    return render_to_response('newsearch/search.html', {'results': results,
-                                                        'did_you_mean': (query is not None) and
-                                                        did_you_mean(query, srch.get_tokens(query, field='SIMPLE')),
-                                                        'fuzzy': fuzzy},
-                              context_instance=RequestContext(request))
+        if len(results) == 1:
+            if len(results[0].hits) == 0:
+                return HttpResponseRedirect(results[0].book.get_absolute_url())
+            elif len(results[0].hits) == 1 and results[0].hits[0] is not None:
+                frag = Fragment.objects.get(anchor=results[0].hits[0])
+                return HttpResponseRedirect(frag.get_absolute_url())
+        elif len(results) == 0:
+            form = PublishingSuggestForm(initial={"books": query + ", "})
+            return render_to_response('catalogue/search_no_hits.html',
+                                      {'tags': tag_list, 'prefix': query, "pubsuggest_form": form,
+                                       'form': forms.SearchForm()},
+                context_instance=RequestContext(request))
+
+        return render_to_response('catalogue/search_multiple_hits.html',
+                                  {'tags': tag_list, 'prefix': query,
+                                   'results': results, 'from': forms.SearchForm()},
+            context_instance=RequestContext(request))
+
+    # return render_to_response('newsearch/search.html', {'results': results,
+    #                                                     'did_you_mean': (query is not None) and
+    #                                                     did_you_mean(query, srch.get_tokens(query, field='SIMPLE')),
+    #                                                     'fuzzy': fuzzy},
+    #                           context_instance=RequestContext(request))
index b569e7d..23d1a59 100644 (file)
@@ -7,9 +7,46 @@
 {% block bodyid %}tagged-object-list{% endblock %}
 
 {% block body %}
-    <h1>{% title_from_tags tags %}</h1>
-    {% breadcrumbs tags %}
+    <form action="{% url search %}" method="get" accept-charset="utf-8" id="search-form">
+        <p>{{ form.q }} <input type="submit" value="{% trans "Search" %}" /> <strong>{% trans "or" %}</strong> <a href="{% url main_page %}">{% trans "return to main page" %}</a></p>
+    </form>
 
+    <div id="results">
+      <ol>
+      {% for result in results %}
+      <li>
+       <p><a href="{{result.book.get_absolute_url}}">{{result.book.pretty_title}}</a> (id: {{result.book_id}}, score: {{result.score}})</p>
+       <ul>
+         {% for hit in result.hits %}
+         <li>
+           {% for snip in hit.3.snippets %}
+             {{snip|safe}}<br/>
+           {% endfor %}
+         </li>
+         {% endfor %}
+
+         {% for part in result.parts %}
+         {% if part.header %}
+         <li>W {{part.header}} nr {{part.position}}</li>
+         {% else %} 
+         {% if part.fragment %}
+         <li>
+           <div style="">Tagi/Motywy: {% for tag in part.fragment.tags %}{{tag.name}} {% endfor %}</div>
+           {{part.fragment.short_html|safe}}
+         </li>
+         {% endif %}
+         {% endif %}
+         {% endfor %}
+       </ul>
+      </li>
+      {% empty %}
+      <p>No results.</p>
+      {% endfor %}
+      </ol>
+    </div>
+
+
+{% comment %}
     <div id="books-list">
         <p>{% trans "More than one result matching the criteria found." %}</p>
         <ul class='matches'>
@@ -24,6 +61,7 @@
         {% endfor %}
         </ul>
     </div>
+{% endcomment %}
 
     <div id="set-window">
         <div class="header"><a href="#" class="jqmClose">{% trans "Close" %}</a></div>
@@ -31,4 +69,4 @@
             <p><img src="{{ STATIC_URL }}img/indicator.gif" alt="*"/> {% trans "Loading" %}</p>
         </div>
     </div>
-{% endblock %}
\ No newline at end of file
+{% endblock %}
index ad7fd15..c494ca6 100644 (file)
@@ -10,7 +10,7 @@
 
 {% block body %}
     <h1>Search</h1>
-    <form action="{% url newsearch %}" method="get" accept-charset="utf-8" id="search-form-x">
+    <form action="{% url search %}" method="get" accept-charset="utf-8" id="search-form-x">
         <p>
          <input type="text" name="q" value="{{request.GET.q}}" style="width:250px; font-size: 1.2em;">
          <input type="submit" value="{% trans "Search" %}" /> 
@@ -32,7 +32,7 @@
          {% for hit in result.hits %}
          <li>
            {% for snip in hit.3.snippets %}
-           {{snip}}<br/>
+             {{snip|safe}}<br/>
            {% endfor %}
          </li>
          {% endfor %}