本文介绍了从数据库Django的自动完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样一个模型:
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)
我想按照这个模型的标题字段模板自动完成输入。我只是想为自动完成标题别的不会为我工作?我觉得应该使用jQuery做,AJAX等。我没有任何关于他们的想法。
有没有办法做到这一点?有没有完全一样的东西的包?
谢谢你。
I want to autocomplete an input in template according to this model's title field. I just want autocomplete for title anything else would not work for me? I think it should be done with jquery, ajax etc. I don't have any idea about them.Is there any way to do this? Is there any packages for exact same thing?Thanks.
推荐答案
pretty好这一点。
ui-autocomplete-input works pretty well for this.
在生成模板列表
<script>
$(function() {
var availableTitles = [
{% for baslik in basliks %}
"{{ baslik.title}}" {% if not forloop.last %},{% endfor %}
{% endfor %}
];
$( "#tags" ).autocomplete({
source: availableTitles
});
});
</script>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
修改(以评论):增加了一个JSON响应;这将需要在两个用户界面,自动完成和自举/ typeahead.js解决方案
EDIT (based on comments): Added a json response; this would be needed in both the ui-autocomplete and bootstrap/typeahead.js solution
import json
from django.http import HttpResponse
def json_response_view(request):
q = request.GET.get('q', '')
response_data = Baslik.objects.filter(title__startswith=q).values("title")
return HttpResponse(json.dumps(response_data), content_type="application/json")
这篇关于从数据库Django的自动完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!