我的自动填充表格工作正常,即。它正确完成数据。现在我希望可以访问这些数据 - >将我链接到有效的网址。 我试着让它自己工作,但我来到了一堵墙。
有人可以给我一个工作示例的提示或链接。 谢谢你的时间。
views.py
def paper_autocompleate(request):
if request.is_ajax():
q = request.GET.get('term', '')
autoPaperwork = Paperwork.objects.filter(
Q(title__icontains=q) | Q(description__icontains=q))[:10]
results = []
for p in autoPaperwork:
p_json = {}
p_json = p.title
results.append(p_json)
data = json.dumps(results)
else:
data = 'fail'
mimetype = 'application/json'
return HttpResponse(data, mimetype)
urls.py
urlpatterns = patterns('',
url(r'^api/paper_autocompleate/', 'papers.views.paper_autocompleate', name='paper_autocompleate')
)
JQAuto.js
$(function() {
$("#autoPaperwork").autocomplete({
source: "/api/paper_autocompleate/",
minLength: 2,
});
});
的index.html
<div class="ui-widget">
<input id="autoPaperwork">
</div>
答案 0 :(得分:1)
未经测试,但我认为您需要这样做:
def paper_autocompleate(request):
if request.is_ajax():
q = request.GET.get('term', '')
autoPaperwork = Paperwork.objects.filter(
Q(title__icontains=q) | Q(description__icontains=q))[:10]
results = []
for p in autoPaperwork:
results.append(p.title)
data = json.dumps(results)
else:
data = 'fail'
mimetype = 'application/json'
return HttpResponse(data, content-type=mimetype)
不确定你的p_json
在做什么,但是我的JQuery-UI自动完成功能通过jsut工作,只是简单的json列表
["result 1", "result 2"]
我使用json.dumps(<python_list_object>)
编辑:这是我的代码,用于任何db对象字段的通用get sorted autocompete
obj = apps.get_model(app_label=app_name, model_name=model_name)
#obj = locate('LessonApp.models.%s' % otype) # old way of locating
try:
search_list = list(obj.objects.\
exclude(Q(**{field: ''}) | Q(**{'{0}__isnull'.format(field): True})).\
values_list(field, flat=True).distinct().order_by(field))
if q:
search_list = filter(lambda s: s[:len(q)].lower() == q.lower(), search_list) # search the list for q, ignore case
return HttpResponse(json.dumps(search_list), content_type='application/json')
except Exception as ex:
return HttpResponse('{"result": "error", "error": "DB Error\n%s"}' % ex, content_type='application/json')
编辑:这是我的javascript来调用我的输入
$('#id_group_name').autocomplete({
source: "/autocomplete/cec_cms/CmsNews/group_name",
minLength: 0,
delay: 500 //default is 300
}).focus(function() {
$(this).autocomplete('search', $(this).val());
});