0

I am using django for my project. Here is the view that I have created to get suggestions for a query:

def query_suggestions(request):
 if request.GET.has_key('term'):
   cols = Col.objects.filter(name__istartswith = request.GET['term'])[:3]
   fes = Fe.objects.filter(name__istartswith=request.GET['term'])[:3]
   users = User.objects.filter(first_name__istartswith=request.GET['term'])[:3]
   json_str = ""
   if users:
    json_str = json.dumps([{'label': user.first_name, 'value': '/'+ user.username + '/'} for user in users])
   if cols:
     json_str += json.dumps([{'label': col.name, 'value': col.get_absolute_url()} for col in cols])
   if fes:
     json_str += json.dumps([{'label': fe.name, 'value': fe.get_absolute_url()} for fe in fes])
   return HttpResponse(json_str)
 return HttpResponse()

This the script using jQuery for autocompletion:

$("#header-search-input").autocomplete({
      source: "/query_suggestions/",
      focus: function (event, ui) {
        $(event.target).val(ui.item.label);
        return false;
      },
      select: function (event, ui) {
        $(event.target).val(ui.item.label);
        window.location = ui.item.value;
        return false;
      }
    });

So, an input value m returns the HttpResponse() of [{"value": "/moni/", "label": "Moni"}, {"value": "/manisha/", "label": "Manisha"}][{"value": "/col/mira/", "label": "Mira"}]

BUt, this doesn't show the autocompletion suggestion under the search-input-bar. But, if I input mo it gives back [{"value": "/moni/", "label": "Moni"}] along with the suggestion under search-input-bar. What's the reason for this?

1 Answer 1

1

The code does not produce valid JSON, as you can see from your example: there is no comma between the lists.

You don't want to produce JSON by concatenating strings. Instead, build up lists or dicts in Python, then dump to JSON at the end:

data = []
if users:
  data.append([{'label': user.first_name, 'value': '/'+ user.username + '/'} for user in users])
if cols:
  data.append([{'label': col.name, 'value': col.get_absolute_url()} for col in cols])
if fes:
  data.append([{'label': fe.name, 'value': fe.get_absolute_url()} for fe in fes])
json_str = json.dumps(data)
Sign up to request clarification or add additional context in comments.

2 Comments

I think the output should be: [{"value": "/moni/", "label": "Moni"}, {"value": "/manisha/", "label": "Manisha"},{"value": "/col/mira/", "label": "Mira"}]. And your answer produces this: [[{"value": "/moni/", "label": "Moni"}, {"value": "/manisha/", "label": "Manisha"}], [{"value": "/col/mira/", "label": "Mira"}]]. So, it still isn't right.
If that's what you want, you can use extend instead of append.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.