ediordna
ediordna

Reputation: 309

Add w3school autocomplete functionality to django form field

i want to add the w3school.com autocomplete functionality to one of my django form fields. At first I used a simple html form and it worked, but after implementing the django-way of working with forms and models, I can't get the autocomplete to work anymore. Here is the relevant part of my code:

forms.py

class PlantForm(forms.ModelForm):
class Meta:
    model = Plant
    fields = ('plantname')
    widgets = {
        'plantname': forms.TextInput(attrs={'placeholder': 'Trage hier den Namen des gelieferten Produkts ein.',
                                            'class': 'autocomplete',
                                            'autocomplete': 'off'}),

models.py

class Plant(models.Model):
     plantname = models.CharField(max_length=255)

main.js

const plants = ["Strauß", "Pepperoni", "Physalis", "Aster"];

window.onload = function () {
    autocomplete(document.getElementById("id_plantname"), plants);
};

index.html

<link rel="stylesheet" href= "{% static 'xyz/index.css' %}">
<script src="{% static 'xyz/main.js' %}"></script>

<form autocomplete="off" method="post">
 {% csrf_token %}
    {{ form|crispy }}
 <button type="submit" class="btn btn-primary">Eintragen</button>
</form>

The css and js code is copy and paste from the w3schools tutorial. I guess it has something to do with the autocomplete class. Maybe it is assigned wrong in the forms.py? The id of the field in main.js should be right according to the django documentation and my tests. Hope you can help me, many thanks in advance.

Upvotes: 0

Views: 461

Answers (1)

AzyCrw4282
AzyCrw4282

Reputation: 7744

It's always best to use a library to achieve an auto-complete feature than use some code from w3school.

Use jQuery and achieve the same feature efficiently with much fewer code

Firstly, create a some_file.json and keep the data that you want to use to autocomplete. E.g.

{
    "something" : null
}

Import jQuery and add the following code to your x.js file. Change it to fit your needs.

    $.getJSON('/static/some_dir/x.json', function(data_) {
        $('input.autocomplete').autocomplete({
            data: data_,
            limit: 20,
            minLength: 2
        });
    });

In x.html file, define your input tag like below

<input title="something" type="text" class="autocomplete" autocomplete="off">

Once implemented, this should do exactly what you want.

Upvotes: 1

Related Questions