简体   繁体   English

在Django项目中使用typeahead.js

[英]Using typeahead.js in Django project

I have a django project with a movie database and would like my search box to simply implement the autocomplete function that typeahead.js gives me. 我有一个带有电影数据库的django项目,希望我的搜索框简单地实现typeahead.js给我的自动完成功能。 I am using this because of its template capabilities and because it fits in well with Bootstrap which is what I'm using for the styling. 我之所以使用它,是因为它具有模板功能,并且与Bootstrap非常吻合,这正是我正在使用的样式。

urls.py urls.py

url(r'^get_movie/$', views.get_movie, name = 'get_movie')

views.py views.py

def get_movie(request):
   results = []
   q = request.GET['q']
   movies = Movie.objects.filter(title__icontains = q)
   results = [ {movie.id: movie.name} for movie in movies ]
   data = json.dumps(results)
   return HttpResponse(data, content_type = 'application/json')

HTML search box HTML搜索框

<input id="searchBox" type="text" class="form-control input-lg typeahead" placeholder="Search a movie..." name="q"></input>

Obviously I have jQuery, Bootstrap and typeahead.js included. 显然,我包含了jQuery,Bootstrap和typeahead.js。

Above is all the necessary code except for the javascript that implements the typeahead.js 上面是所有必需的代码,除了实现typeahead.js的javascript之外

This is an example from the official website but I don't know what modifications I would need to apply to be able to dynamically obtain the results from my database and show them in the autocomplete list: 这是来自官方网站的示例,但我不知道我需要进行哪些修改才能从数据库中动态获取结果并将其显示在自动完成列表中:

<script type="text/javascript">
  $('.typeahead').typeahead(null, {
    name: 'best-pictures',
    display: 'value',
    source: bestPictures,
    templates: {
      empty: [
        '<div class="empty-message">',
          'unable to find any Best Picture winners that match the current query',
        '</div>'
      ].join('\n'),
      suggestion: Handlebars.compile('<div><strong>{{value}}</strong> – {{year}}</div>')
    }
  });
</script>

Hint: I'm pretty sure I need to use Ajax to obtain the "source" list but have tried and can't manage to do it. 提示:我很确定我需要使用Ajax来获取“源”列表,但是已经尝试并且无法做到这一点。

I would suggest using the "remote" version. 我建议使用“远程”版本。 Try this: 尝试这个:

urls.py: urls.py:

url(r'^get_movie/$', SearchListView.as_view(), name='get_movie'),
url(r'^ajaxsearch/$', views.search_ajax, name='search_ajax')

views.py: views.py:

from django.db.models import Q
from django.views.generic.list import ListView

class SearchListView(ListView):
    model = Movie
    template_name = 'some_template.html'

    def get_context_data(self, *args, **kwargs):
        context = super(SearchListView, self).get_context_data(*args, **kwargs)
        context['query'] = self.request.GET.get('q')
        return context

    def get_queryset(self, *args, **kwargs):
        movie_qs = super(SearchListView, self).get_queryset(*args, **kwargs)
        query = self.request.GET.get('q')

        if query:
            user_qs = self.model.objects.filter(
                Q(title__icontains=query)
                )
        return movie_qs


@require_http_methods(['GET'])
def search_ajax(request):
    q = request.GET.get('q')
    data = {}

    if q:
        titles = Movie.objects.filter(title__icontains=q)
        data = [{'title': title} for title in titles]
    return JsonResponse(data, safe=False)

search box: 搜索框:

<div id="remote" class="twitter-typeahead">
    <input type="text" class="form-control input-lg typeahead tt-input" name="q" placeholder="Search a movie..." />
</div>

javascript: JavaScript的:

var titlesDisplay = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('title'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
        url: "{% url 'search_ajax' %}",
        replace: function(url, query) {
            return url + "?q=" + query;
        }
    }
});
$('#remote .typeahead').typeahead({
    minLength: 1,
    highlight: true},
    {name: 'titles-display',
    display: 'title',
    source: titlesDisplay,
});

We ended up using this solution a friend gave to us and it works well: 我们最终使用了一个朋友给我们的解决方案,并且效果很好:

<script type="text/javascript">
  $(document).ready(function(){
    var queryMovies = new Bloodhound({
        datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        limit: 20,
        rateLimitWait: 800,
        remote: {url:'/get_movie/?q=%QUERY', wildcard: '%QUERY'}
    });

    queryMovies.initialize();

    $('#remote .typeahead').typeahead({
        hint: true,
        highlight: true,
        minLength: 2,
    },
    {
        name: 'queryMovies',
        display: 'value',
        source: queryMovies.ttAdapter(),
        templates: {
            empty: [
            '<div class="empty-message">',
            'No hay resultados con la consulta',
            '</div>'
            ].join('\n'),
            suggestion: function(data) {
              var url = "{% url 'movie' '00000' %}"
              url = url.replace('00000', data.id);
              return '<div><p><a href="' + url + '">' + data.title + '</a></p></div>';
            }
        }
    });
  });
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM