我正在尝试使用typehhead.js的猎犬输入从我的数据库中自动完成 我有这样的模型:
class Baslik(models.Model):
user = models.ForeignKey(User, null=True, blank=True)
title = models.CharField(max_length=50)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
active = models.BooleanField(default=True)
我希望根据此模型的标题字段进行自动完成。
我把这些js代码放到我的base.html
<script type="text/javascript">
// constructs the suggestion engine
var states = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
// `states` is an array of state names defined in "The Basics"
local: $.map(states, function(state) { return { value: state }; })
});
// kicks off the loading/processing of `local` and `prefetch`
states.initialize();
$('#bloodhound .typeahead').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'states',
displayKey: 'value',
// `ttAdapter` wraps the suggestion engine in an adapter that
// is compatible with the typeahead jQuery plugin
source: states.ttAdapter()
});
</script>
<script type="text/javascript">
var source = new Bloodhound({
hint: false,
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('description'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: YOUR_JSON_VIEW_URL + '&query=%QUERY'
});
source.initialize();
</script>
<script type="text/javascript">
$(typeahead_input).typeahead(null, {
name: 'some_name',
displayKey: 'description',
source: source.ttAdapter() }
</script>
我也有这个输入标签自动完成:
<form class="ui icon input" role="form" action="/baslik/">
<div id="bloodhound">
<input class="typeahead" type="text" placeholder="Ara..." id="input_lookup">
</div>
<i class="search link icon"></i>
<input type="submit" style="position: absolute; left: -9999px"/>
</form>
我有这个观点:
from django.views.generic import View
import json
class MyJsonView(View):
def get(self, request):
context = []
querystring = request.GET.get('query', None)
if querystring:
instances = MyModel.objets.filter(somefield__icontains=querystring)
for ins in instances:
context.append({'id': ins.id, 'description': ins.display_title})
json_context = json.dumps(context)
return HttpResponse(json_context, {'content_type': 'application/json'})
这是我项目中的网址urls.py:
url(r'^search_my_model/$', MyJsonView.as_view(), name='search_my_model')
我不知道我在这些部分中犯了错误。我怎样才能做到这一点?任何想法都会有帮助。感谢。