DjangSelective在焦点上显示自动完成选项

2024-05-20 20:45:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在焦点上显示自动完成选项。如果输入值为空,我想显示所有选项。我想要的行为相当于以下效果:

<!DOCTYPE html>
<html>
    <head>
        <meta charset=utf-8/>
        <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
    </head>
    <body>
        <input id="text" type="text"></input>
        <script>
            $(
                function() {
                    $('#text').autocomplete(
                        { source: ['abc', 'bcd', 'cde'], minLength: 0 }
                    ).focus(function() { $(this).autocomplete('search'); });
                }
            );
        </script>
    </body>
</html>

如何使用Django selective完成此操作?在


Tags: texthttpssrccomuihtmltype选项
1条回答
网友
1楼 · 发布于 2024-05-20 20:45:52

你有没有机会阅读一份自动完成的文档?在

尤其是关于source选项?在

基本上,您需要在您的端创建一个服务,这个服务将返回JSON格式的数据,它可以是字符串列表([“Choice1”,“Choice2”]),包含“label”和“value”键的记录列表([{label:“Choice1”,value:“value1”}。。。]),或任何其他数据—在这种情况下,您需要另外编写数据解析函数。在

对于搜索功能,您的服务应该接受“term”查询参数(例如:http://example.com?term=foo)。在

要在Django中编写此代码,请创建一个视图(无论是否基于类),该视图将响应GET请求、查询数据库并返回格式为JSON的数据(响应中包含适当的content/type头)

class MyDict(models.Model):
    name = models.CharField(max_length=100, db_index=True)

    class Meta:
        ordering = ['name']

def search_view(request):
    term = request.get('term')
    search = {}
    if term:
        search['name__icontain'] = term
    # we are limiting answers to not dump whole db over the ajax
    # user has a possibility to narrow search
    result = [{'label': o.name, 'value': o.name} for o in MyDict.objects.filter(**search)[:50]]
    return HttpResponse(json.dumps(result), mimetype='application/json')

相关问题 更多 >