【问题标题】:Add w3school autocomplete functionality to django form field将 w3school 自动完成功能添加到 django 表单字段
【发布时间】:2020-03-02 21:40:13
【问题描述】:

我想将w3school.com autocomplete functionality 添加到我的 django 表单字段之一。起初我使用了一个简单的 html 表单并且它可以工作,但是在实现了使用表单和模型的django-way 之后,我无法再让自动完成功能工作了。 这是我的代码的相关部分:

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>

css 和 js 代码是从w3schools tutorial 复制和粘贴的。 我想这与自动完成类有关。也许它在forms.py中分配错误?根据 django 文档和我的测试,main.js 中字段的 id 应该是正确的。希望你能帮助我,非常感谢。

【问题讨论】:

    标签: django python-3.x django-models autocomplete django-forms


    【解决方案1】:

    最好使用库来实现自动完成功能,而不是使用 w3school 的一些代码。

    使用jQuery 并以更少的代码高效地实现相同的功能

    首先,创建一个some_file.json 并保留要用于自动完成的数据。 例如

    {
        "something" : null
    }
    

    导入 jQuery 并将以下代码添加到您的 x.js 文件中。 更改它以满足您的需求。

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

    在 x.html 文件中,定义您的输入标签,如下所示

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

    一旦实施,这应该完全符合您的要求。

    【讨论】:

    • 解决了吗?如果是这样,请接受答案以表明它已解决。
    • 嗨 Azy_Crw4282,非常感谢您的回答!我在不使用单独的 .json 文件的情况下成功实现了它。但它只是直接在 xx.html 中工作。在 x.js 文件中编写完全相同的代码时,我不知道为什么它不起作用。导入工作。
    猜你喜欢
    • 1970-01-01
    • 2021-06-15
    • 1970-01-01
    • 1970-01-01
    • 2022-10-25
    • 2014-09-15
    • 2015-02-14
    • 2014-09-28
    • 2018-03-28
    相关资源
    最近更新 更多