> For the complete documentation index, see [llms.txt](https://olee-tech.gitbook.io/django/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://olee-tech.gitbook.io/django/undefined-6/autocomplete-show-multiple-fields/autocomplete-search.md).

# 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>
