[英]How to use django-autocomplete-light
如何使用django_autcomplete_light将自动填充添加到表单中的一个字段。 我有一个基于模型的表单,我想在firstname字段中添加自动完成功能。
到目前为止我做了以下事情:
安装django_autocomplete_light
更改了INSTALLED_APPS:
INSTALLED_APPS = (
'autocomplete_light',
'django.contrib.admin',
...
将它添加到urls.py,这是我的urls.py:
来自django.conf.urls的import include,来自django.contrib的url导入管理员
urlpatterns = [
url(r"^admin/", include(admin.site.urls)),
url(r"^app/", include("app.urls")),
url(r"^autocomplete/", include("autocomplete_light.urls")),
url(r"^.*$", include("app.urls")),
]
创建了一个名为autocomplete_light_registry.py的文件,并添加了以下内容:
import autocomplete_light as al
from .models import *
al.register(Person,
search_fields = ["^firstname"],
attrs={
"placeholder":"First name",
"data-autocomplete-minimum-characters":1,
},
widget_attrs={
"data-widget-maximum-values":4,
"class":"modern-style",
},
)
改变了我的PersonForm:
class PersonForm(forms.ModelForm)
至:
class PersonForm(autocomplete_light.ModelForm)
class Meta:
model = Person
autocomplete_fields = ("firstname")
我还将以下行添加到表单的html页面:
{% include 'autocomplete_light/static.html' %}
我导入了所有必要的jquery文件
但是自动完成功能不会出现。 我没有得到任何错误。 我按照文档教程。
我使用python manage.py runserver
来运行应用程序。
编辑:
我将urlpatterns更改为(首先制作了django-autocomplete-light url):
urlpatterns = [
url(r"^autocomplete/", include("autocomplete_light.urls")),
url(r"^admin/", include(admin.site.urls)),
url(r"^app/", include("app.urls")),
url(r"^.*$", include("app.urls")),
]
但这并没有解决问题。
如果使用django-autocomplete-light
搜索models.CharField
则必须执行不同的操作。 在form.py中,您需要将以下小部件添加到要添加自动完成的字段中:
autocomplete_light.TextWidget("PersonAutocomplete")
例如forms.py:
from django import forms
import autocomplete_light
from .models import *
class PersonForm(forms.ModelForm):
"""
This form is to create new RTN's. It does not include lastupdateddate and
lastupdatedby, because these will be automatically filled out.
"""
class Meta:
model = Rtn
autocomplete_fields = ("firstname")
fields = ["firstname", "lastname", "age"]
widgets = {
"firstname":autocomplete_light.TextWidget("PersonAutocomplete"),
}
您应该注意,自动完成中显示的内容将是您在模型类中的__str__
或__unicode__
函数中返回的__str__
。 在我的示例中,我的Persons类具有以下__unicode__
方法:
def __unicode__(self):
return "{0} {1}".format(self.firstname, self.lastname)
因此,正在自动完成的文本字段中显示的内容将是该人员的全名,而不仅仅是名字,如果您选择一个,则在该字段中输入全名。
根据本教程,我认为您的代码没有意义。 您需要与另一个模型(不仅仅是示例中的一个)的foreign key
或many-to-many
关系来自动填充表单字段。 在教程示例中, birth_country
在PersonForm
自动完成,如下所示:
//forms.py
class PersonForm(forms.ModelForm):
class Meta:
model = Person
fields = ('__all__')
widgets = {
'birth_country': autocomplete.ModelSelect2(url='country-autocomplete')
}
表单代表所有Person
字段并覆盖birth_country
自动完成。
此外,被告知dal插件已经在版本3中,并且与您的代码非常不同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.