Django - JQuery autocomplete custom select from multiple fields

80
July 20, 2021, at 04:30 AM

I have a user search that autocompletes by both ticker and name. The search results come back as "{{ticker}} - {{name}}". When a result is selected, I want it to fill with only the ticker, where as it currently fills with "{{ticker}} - {{name}}".

Here is my python code:

if 'term' in request.GET:
    tickers = Company.objects.filter(ticker__istartswith = request.GET.get('term')) | Company.objects.filter(name__istartswith = request.GET.get('term'))
    companies = []
    for ticker in tickers:
        companyTicker = ticker.ticker +  " - " + ticker.name
        companies.append(companyTicker)
    return JsonResponse(companies, safe=False)

and here is my javascript:

    <script>
    $( function() {
      $( "#ticker3" ).autocomplete({
        source: '{% url "financials:get_financials" %}',
        select: function (event, ui) {
            ticker.ticker
        }
      });
    } );
    </script>

Any help greatly appreciated!

Answer 1

A quick look at the jquery autocomplete docs reveals that you can use an array of objects for your source option. Each object should have a label and value attribute. The following should get you what you need.

if 'term' in request.GET:
    tickers = Company.objects.filter(ticker__istartswith = request.GET.get('term')) | Company.objects.filter(name__istartswith = request.GET.get('term'))
    companies = []
    for ticker in tickers:
        label = f"{ticker.ticker} - {ticker.name}"
        companyTicker = {'label': label, 'value': ticker.ticker}
        companies.append(companyTicker)
    return JsonResponse(companies, safe=False)

You can then remove the select option in your javascript:

  <script>
      $(function () {
          $("#ticker3").autocomplete({
              source: '{% url "financials:get_financials" %}',
          });
      });
  </script>
READ ALSO
How good implement method? [closed]

How good implement method? [closed]

Want to improve this question? Update the question so it's on-topic for Stack Overflow

54
Python relative import in subdirectory

Python relative import in subdirectory

I have a Python project, which has something like the following structure:

68