我想将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应该正确。希望您能帮助我,在此先多谢。
答案 0 :(得分: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">
实施后,这应该可以完全满足您的要求。