# Autocomplete Search

### models.py

```python
from django.db import models

# Create your models here.
class City(models.Model):
    name = models.CharField(max_length=100)
    population = models.IntegerField()
```

### admin.py

```python
from django.contrib import admin
from .models import City
# Register your models here.

admin.site.register(City)
```

<div><figure><img src="/files/ro5dsTnQylv0O2wBlRbW" alt=""><figcaption></figcaption></figure> <figure><img src="/files/B5lTTEk95Wx5aZTbUWfi" alt=""><figcaption></figcaption></figure></div>

### views.py

```
from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from .models import City
# Create your views here.
def home(request):
  return render(request,'autocomplete/index.html')

def autocomplete(request):
    term = request.GET.get('term', '')
    suggestions = City.objects.filter(name__icontains=term).values_list('name', flat=True)
    return JsonResponse(list(suggestions), safe=False)
```

### Templates

**templates/autocomplete/index.html**

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
    <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.1/themes/smoothness/jquery-ui.css">
</head>
<body>
    <input type="text" id="my-input" name="my-input" />
    <script>
        $(function() {
            $('#my-input').autocomplete({
                source: '{% url "autocomplete" %}',
                minLength: 2,
            });
        });
        </script>
</body>
</html>
```

### urls.py

```python
from django.urls import path
from . import views
urlpatterns = [
    path('',views.home,name='home'),
    path('autocomplete/', views.autocomplete, name='autocomplete'),
]
```

<figure><img src="/files/J0mzlSTgDy8AvsdWPbcO" alt=""><figcaption></figcaption></figure>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://olee-tech.gitbook.io/django/undefined-6/autocomplete-show-multiple-fields/autocomplete-search.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
