Django JQuery自动完成显示没有搜索结果

时间:2016-01-17 07:41:12

标签: jquery django jquery-autocomplete

我将直接转到代码

models.py

class Restaurant(models.Model):
    name = models.CharField(max_length=100)
    owner = models.CharField(max_length=100)
    city = models.CharField(max_length=50)
    state = models.CharField(max_length=50)
    country = CountryField(choices=list(countries))
    contact = models.CharField(max_length=15)
    def __str__(self):
        return self.name

template.html

{% load staticfiles %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Dashboard</title>
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
    <script src="{% static 'registration/jquery.js' %}"></script>
</head>
<body>
    <input id="tags"/>
</body>
</html>

的jquery.js

$(document).ready(function(){
 $( "#tags" ).autocomplete({
                        source: "{% url get_restaurant %}",
                        selectFirst: true,
                        minLength: 2
    });
});

urls.py

url(r'^get_restaurant/$', views.get_restaurant, name='get_restaurant')

views.py

def get_restaurant(request):
    term = request.GET.get('term')
    bslk = Restaurant.objects.filter(name__icontains=term)
    res = []
    for b in bslk:
        dict = {'id':b.id, 'label':b.name, 'value':b.name}
        res.append(dict)
    return HttpResponse(simplejson.dumps(res),'application/json')

我使用了以下导入:

import simplejson用于views.py

我在餐厅模型中有姓名值,但问题是自动填充显示No search results!

提前谢谢!

1 个答案:

答案 0 :(得分:1)

jquery.js是一个静态文件,不会被django模板引擎预处理。因此,您必须将{% url %}标记替换为硬编码网址:

$(document).ready(function(){
   $( "#tags" ).autocomplete({
                        source: "/get_restaurant/",
                        selectFirst: true,
                        minLength: 2
   });
});

或以某种方式将此url从模板传递给js。例如:

<script>
    var restaurantAutocompleteUrl = "{% url 'get_restaurant' %}";
</script>
<script src="{% static 'registration/jquery.js' %}"></script>

然后在JS文件中:

$(document).ready(function(){
   $( "#tags" ).autocomplete({
                        source: restaurantAutocompleteUrl,
                        selectFirst: true,
                        minLength: 2
   });
});

另一种选择是将JS绑定代码包装到函数中,并从模​​板中调用此函数:

<script src="{% static 'registration/jquery.js' %}"></script>
<script>
    bindAutocomplete("#tags", "{% url 'get_restaurant' %}");
</script>