Javascript Django和typeahead.js出现问题
我正试图用typeahead.js的血猎犬从数据库中自动完成输入 我有这样的模型:Javascript Django和typeahead.js出现问题,javascript,jquery,python,django,typeahead.js,Javascript,Jquery,Python,Django,Typeahead.js,我正试图用typeahead.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) up
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>
这是我在项目url.py中的url:
url(r'^search_my_model/$', MyJsonView.as_view(), name='search_my_model')
我不知道我在哪一部分犯了错误。我怎样才能做到这一点?任何想法都会有帮助。谢谢。在settings.py所在的目录中,您的\u JSON\u VIEW\u URL定义在哪里?您的观点是什么?我想我误解了。在javascript代码中,文本“YOUR_JSON_VIEW_URL”实际上是这样存在的,还是您只是用一些伪文本替换了实际的URL?如果这是真的,那么它就是一个变量:变量集的值在JS中的什么位置?实际上我对这些代码中的JS部分不太了解。我只是用了这里的密码<代码>http://stackoverflow.com/questions/25412777/django-autocomplete-from-db/25413211?noredirect=1#comment39738982_25413211所以不幸的是我不知道。如果您比我更了解如何处理此链接中的答案,请让我知道。
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'})
url(r'^search_my_model/$', MyJsonView.as_view(), name='search_my_model')