Django项目中的typeahead.js

https://twitter.github.io/typeahead.js/examples/上有一些例子我需要在我的django app中做类似的搜索主题标签。 但我尝试过它并不起作用。 有一个类似的问题,并在stackoverflow上得到了一个,但我不明白如何做到这一点。 在Django项目中使用typeahead.js

views.py

class SearchTag(View): """ Search tags with autocomplete (live search) """ def get(self, request): form = SearchTagForm() context = {'searchtag' : form} return render(request, 'search_tags.html', context) def post(self,request): q = request.POST['q'] form = SearchTagForm() tags = HashTag.objects.filter(name__icontains=q) context = {'tags' : tags, 'searchtag' : form} return render(request, 'search_tags.html', context) class TagJson(View): """Search a hashTag with auto complete feature""" def get(self, request): q = request.GET.get('q','') taglist = [] tags = HashTag.objects.filter(name__icontains=q) for tag in tags: new = {'q' : tag.name} taglist.append(new) return HttpResponse(json.dumps(taglist), content_type="application/json") 

models.py

 class HashTag(models.Model): ''' HashTag model ''' name = models.CharField(max_length = 100, unique = True) post = models.ManyToManyField(Post) def __str__(self): return self.name 

forms.py

 class SearchTagForm(forms.Form): q = forms.CharField(widget=forms.TextInput(attrs={ 'size' : 30, 'class' : 'form-control search-tag-query typeahead', 'id' : 'typeahead' })) 

而在HTML中它看起来像这样

  

我连接了typahead.bundle.js,还有一个文件search_tag.js search_tag.js

 var hashTags = new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'), queryTokenizer: Bloodhound.tokenizers.whitespace, prefetch: '/hashtag.json?q=%QUERY', remote: { url: '/hashtag.json?q=%QUERY', wildcard: '%QUERY' } }); $('#typeahead').typeahead(null, { name: 'hashTags', display: 'value', source: hashTags }); 

urls.py

  url(r'^hashtag.json$', TagJson.as_view(), name = 'tagjson') 

如果我去http://127.0.0.1:8000/hashtag.json?q=h我得到[{“q”:“#hashtag”},{“q”:“#hashtags”}]

在我的浏览器开发者控制台中,我得到这个输入每个键。

jquery-3.2.1.min.js:4 XHR完成加载:获取“ http://127.0.0.1:8000/hashtag.json?q=h ”。

jquery-3.2.1.min.js:4 XHR完成加载:获取“ http://127.0.0.1:8000/hashtag.json?q=ha ”。

可能一切正常。 但仍然是预先输入不起作用所以我可以在本页的例子中看到它https://twitter.github.io/typeahead.js/examples/我不明白它是什么问题

search_tag.js的这段代码使一切都按照我在顶部的所有其他代码工作。 这是我写的video,如何连接typeahead.js,但它是我的母语俄语: https : //www.youtube.com/watch?v = lwOHnWSCYFc如果你有相同的问题,一定要检查差异我的search_tag.js位于顶部,这个,您将看到您需要更改的内容。

 var hashTags = new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.obj.whitespace('q'), queryTokenizer: Bloodhound.tokenizers.whitespace, prefetch: '/hashtag.json?q=%QUERY', remote: { url: '/hashtag.json?q=%QUERY', wildcard: '%QUERY' } }); $('#typeahead').typeahead(null, { name: 'hashTags', displayKey: 'q', source: hashTags.ttAdapter() });