0

I'm implementing an autocomplete search using jQuery UI and Django models.

Here is my view:

def get_ticker(request):
    if request.is_ajax():
        q = request.GET.get('term', '')
        symbols = Symbol.objects.filter(name__istartswith=q)
        results = []
        for symbol in symbols:
            symbol_json = {'name': symbol.name, 'symbol': symbol.symbol}
            results.append(symbol_json)
        data = json.dumps(results)
    else:
        data = 'Can\'t get data...'
    mimetype = 'application/json'
return HttpResponse(data, mimetype)

url:

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

js:

$(function() {
   $("#ticker").autocomplete({
      source: "{% url get_ticker %}",
      minLength: 2,
   });
});

html:

 <div class="ui-widget">
      <input type="text" id="ticker">
 </div>

When I type in search box, I get error:

GET http://127.0.0.1:8000/finance/%7B%%20url%20get_ticker%20%%7D?term=hello 404 (NOT FOUND)
Bun
  • 3,037
  • 3
  • 19
  • 29
  • Is the js served as static content or is it rendered? You need to render it (or put the url in the html file, which is probably a better idea). – noamk Jun 03 '15 at 16:54
  • it's is static content. How do rendered it?@noamk – Bun Jun 03 '15 at 16:58
  • There are ways to render static django content (you can find them using google), but that's not a good solution IMHO. This javascript file is served as-is, without changes. The proper way to do this is to put the url in some property in the html (which is rendered), and access the property from the javascript. – noamk Jun 03 '15 at 19:57

3 Answers3

1

I suspect you're serving the JS file separately. If that's the case, then you'll have to:

either write the full URL yourself in the JS file.

source: "/api/get_ticker/",

or copy the script in your HTML template.

<script>
    $(function() {
       $("#ticker").autocomplete({
           source: "{% url 'get_ticker' %}",
           minLength: 2,
       });
   });
</script>
xyres
  • 20,487
  • 3
  • 56
  • 85
  • I think search is working but when I type in, it shows me drop down list without any text. Any ideas? – Bun Jun 03 '15 at 17:23
  • http://stackoverflow.com/questions/12393449/jqueryui-autocomplete-returns-back-empty-list this works for me. – Bun Jun 03 '15 at 17:37
0

Try this:

$(function(){
  $('#ticker').autocomplete({
    source: "{% url 'get_ticker' %}",
    minLength: 2,
  });
});
Gocht
  • 9,924
  • 3
  • 42
  • 81
0

Replace:

 "{% url get_ticker %}"

with

 "{% url 'get_ticker' %}"

Make note of the quotes

kylieCatt
  • 10,672
  • 5
  • 43
  • 51