Skip to content
Advertisement

how to create a autocomplete input field in a form using Django

I am pretty new to django and its ways. I am trying to create an autocomplete field for a form. My code is as below

forms.py

JavaScript

What I want to achieve is that when an user types words into the "From Email" field the list of emails I have stored in an external DB should appear in the autocomplete list option.

models.py

JavaScript

Any idea how this can be done ?

Update :

I started messing around with django-autocomplete-light and now able to get a reply from the autocomplete url. It looks like this

JavaScript

views.py

JavaScript

I still do not know how to get this data to appear in the field "from_email"

Advertisement

Answer

I finally got the autocomplete search working using the instructions found here

https://github.com/xcash/bootstrap-autocomplete
https://bootstrap-autocomplete.readthedocs.io/en/latest/

It is very simple to use and does not need to install any app in settings.py and it works for both bootstrap 3 and bootstrap 4

There are lot of other packages available but this was simple and easy for my need.

I am going to explain the code I used

page.html

JavaScript

autoComplete is the function called to perform the action and minLength specifies the minimum length of the text before performing the fetch action I added an extra CSS to fix the autocomplete dropdown otherwise it was weird.

The Jinja render kept overwriting the class definition from views so I added an if check for it.

urls.py

JavaScript

Added this line to urls.py

forms.py

JavaScript

The above is the code for the input field in forms.py. data-url points to where the JSON result would be generated.

views.py

JavaScript

This was the most confusing part for me. The GET request is easy to understand but it took a while to convert the data from model.objects into a JSON formatted object. The trick was to use

JavaScript

when filtering the data from the database, then converting to a list using list(data) and finally use JsonResponse to convert it to JSON.

Hope this will help any one who wants a simple autocomplete

Advertisement