Logging Django Haystack search keyword
django, django-haystack, python
Solution
I wanted to do something similar so I created an app named search
search/models.py
from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import ugettext as _
class SearchTerm(models.Model):
query = models.CharField(
verbose_name = _(u'Search Term'),
max_length = 255,
default = None
)
class SearchQuery(models.Model):
term = models.ForeignKey(
SearchTerm
)
user = models.ForeignKey(
User,
blank = True,
null = True,
)
when = models.DateTimeField(
verbose_name = _(u'Date Searched'),
)
search/urls.py
from django.conf.urls.defaults import *
urlpatterns = patterns('',
url(r'^search/', 'search.views.search', name="search"),
)
then of course in my project urls I added the following rule:
url(r'^', include('search.urls')),
search/views.py
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, render, redirect
from haystack.forms import ModelSearchForm, SearchForm
from haystack.views import SearchView
from search.models import SearchQuery, SearchTerm
import datetime
def search(request):
if 'page' not in request.GET :
try :
st, created = SearchTerm.objects.get_or_create(query=request.GET['q'])
sq = SearchQuery()
sq.term = st
sq.user = request.user
sq.when = datetime.datetime.now()
sq.save()
except :
pass
view = SearchView()
return view(request)
`if 'page' not in request.GET` so that only on the first page of search results, a SearchQuery is saved
each SearchQuery is unique in the DB.
each SearchQuery for a SearchTerm is recorded with additional info such as `user` (nullable) and `when` the term was searched.
`view = SearchView()` and `return view(request)` make it so that aftera a SearchQuery is recorded, the default haystack views get called for that request.
Problem
I have the following in my url.py: ``` from haystack.forms import HighlightedModelSearchForm from haystack.query import SearchQuerySet from haystack.views import SearchView from articles.models import Article article_sqs = SearchQuerySet().models(Article) urlpatterns = patterns('', ... url(r'^article/search/$', SearchView( template='articles/search/results.html', searchqueryset=article_sqs, results_per_page=10, form_class=HighlightedModelSearchForm ), name='haystack_search'), ... ``` It's working fine but I need to capture the search keyword to log it. How can I capture it? Your help would be appreciated.