我将自动完成数据存储在SomeObject对象中,并成功使用以下内容通过基于当前用户的过滤器自动完成:
views.py
def get_autocompletion_list(request):
if request.is_ajax():
q = request.GET.get('term', '')
results = []
if len(q) > 0:
my_words = SomeObject.objects.filter(owner=request.user.id)
words = my_words.filter(word__startswith=q)
for w in words:
results.append(w.word)
data = json.dumps(results)
else:
data = ''
mimetype = 'application/json'
return HttpResponse(data, mimetype)
模板:
<form action="/" method="post" id="">
{% csrf_token %}
{{form.category}}
</form>
<input id="searching">
脚本:
$("#category_id").change(function () {
console.log("selected category")
console.log($(category_id).val())
});
$(function() {
$("#searching").autocomplete({
source: "/api/get_autocompletion_list/",
select: function (event, ui) {
AutoCompleteSelectHandler(event, ui)
},
minLength: 1,
});
});
现在我想根据form.category下拉列表中的选择来过滤自动完成功能,我能够在窗体中获得当前选择,但是如何将其发送到可以进行过滤的视图中呢? / p>
答案 0 :(得分:0)
通过将当前所选类别的ID添加到用于自动补全的网址中,我就可以将数据发送到django。
//when value is changed in the dropdown
$("#category_id").change(function () {
setAutocompletion()
});
//change the url based on the selected drop down value
function setAutocompletion(){
$("#searching").autocomplete({
source: "/api/get_autocompletion_list/" + getSelectedValue(),
select: function (event, ui) {
AutoCompleteSelectHandler(event, ui)
},
minLength: 1,
});
}
function getSelectedValue() {
var s = $(id_kategori).val()
return String(s)
}
function AutoCompleteSelectHandler(event, ui) {
var selectedObj = ui.item;
}