如何将标签和值的字典传递到jQuery Autocomplete中

问题描述

我正在尝试将标签和值的字典传递到我的模板中,以便可以在jQuery的某个字段上使用自动完成功能。问题是我的字典传递不正确。

我有一个Django模型Question,其中有一个问题(标签)和一个子弹(值)。我想将它们都传递到我的模板中,以便当有人单击问题文本时,我可以将它们重定向到该问题的url / slug。

Question.html

<input id="search-bar" name="question" type="text" class="form-control" placeholder="Find your next question..." aria-label="Find your next question...">

<div class="input-group-append">
    <button id="search-question-button" class="btn" type="submit">Search</button>
</div>

<script>
    $(function () {
        $("[name='question']").autocomplete({
            source: "{% url 'questions' slug=question.slug %}",select: function (event,ui) {
                window.location.href = ui.item.value;
                console.log(ui.item);
                
            }
        });
    });
</script>

Views.py

if 'term' in request.GET:
    qs = current_questions.filter(question__istartswith=request.GET.get('term'))
    qs_dict = dict()

    for question in qs:
        qs_dict['label'] = question.question
        qs_dict['value'] = question.slug
    print(qs_dict)

    return JsonResponse(qs_dict,safe=False)

在我的django项目控制台中,我正在打印此词典,并且看来可以正确打印{'question': "Blah blah blah",'slug': 'blah-blah-blah'}

但是,当我使用chrome浏览我的网站时,发现标签和值相同,并且字典没有正确传递。

编辑:

所以现在我要传递一个查询集列表:

Views.py

if 'term' in request.GET:
    qs = current_questions.filter(question__istartswith=request.GET.get('term'))
    qs_list = []

    for question in qs:
        qs_list.append(qs.values('question','slug'))

    return JsonResponse(qs_list,safe=False)

但是我收到错误TypeError: Object of type QuerySet is not JSON serializable

还,这是否意味着我必须将密钥从“问题”和“子弹”更改为“标签”和“值”?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)