python - Django Taggit - 自动完成灯(配置指南)
问题描述
我已经完全启动并运行了 Taggit,并且想要配置 Autocomplete Light,以便在用户在我的应用程序中选择他们喜欢的标签时启用 Select2 下拉菜单。
我已经安装了DAL
,dal_select2
以及dal_queryset_sequence
库。
我已经创建了一个表单,我的用户可以在其中简单地上传照片、添加内容和 TagField。虽然,TagField 当前作为普通文本字段运行(但标签确实成功保存到我的 Taggit 应用程序) - 我只是在努力让 Select2 下拉菜单正常工作。
这是我的设置(就已安装的应用程序而言:
设置.py
INSTALLED_APPS = [
'core.apps.AConfig',
'users.apps.UConfig',
'crispy_forms',
'emoji_picker',
'taggit',
'dal',
'dal_select2',
'dal_queryset_sequence',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sites',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
]
在我的 Views.py 中
from dal import autocomplete
class TagAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
# Don't forget to filter out results depending on the visitor !
if not self.request.user.is_authenticated():
return Tag.objects.none()
qs = Tag.objects.all()
if self.q:
qs = qs.filter(name__istartswith=self.q)
return qs
URLs.py
from core.views import TagAutocomplete
urlpatterns = [
url(
r'^tag-autocomplete/$',
TagAutocomplete.as_view(),
name='tag-autocomplete',
),
]
表格.py
import dal
from dal import autocomplete
from taggit.models import Tag
class PostForm(autocomplete.FutureModelForm):
tags = forms.ModelChoiceField(
queryset=Tag.objects.all()
)
class Meta:
model = Post
fields = ('__all__')
widgets = {
'tags': autocomplete.TaggitSelect2(
'tag-autocomplete'
)
}
我查看了 Django Autocomplete Light 的文档,但我不太确定从我已有的代码中去哪里。
任何指导将不胜感激!
谢谢!:-)
解决方案
尝试将此代码添加到您拥有表单的 HTML 模板中:
#YourHTMLTemplate.html
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
{{ form.media }}
<script>
(function($) {
$('#add-form').click(function() {
var index = $('#id_inline_test_models-TOTAL_FORMS').val()
var newTable = $('#id_inline_test_models-__prefix__-DELETE').parents('table').clone()
newTable.find(':input').each(function() {
for (attr of ['name', 'id'])
$(this).attr(
attr,
$(this).attr(attr).replace('__prefix__', index)
)
})
newTable.insertBefore($(this))
$('#id_inline_test_models-TOTAL_FORMS').val(
parseInt($('#id_inline_test_models-TOTAL_FORMS').val()) + 1
)
newTable.slideDown()
})
})($)
</script>
之后,下拉菜单应该可以工作。更多细节在这里。
推荐阅读
- twitter-bootstrap - 动态启用和禁用切换按钮
- javascript - 如何使用 React 路由导航到上一个屏幕
- flutter - 如何使用“CupertinoFullscreenDialogTransition”?
- python - Python从键列表生成动态嵌套字典
- typescript - 匹配类验证器装饰器不适用于 type-graphql 自动验证
- javascript - javascript:较大一侧的数组中最接近的数字
- upgrade - 将 hybris 从 6.4 升级到 6.7
- ios - 应用程序在 iOS 10 及更早版本上因“无法实例化名为 _UIScrollViewLayoutGuide 的类”而崩溃
- laravel - Laravel:将当前视图名称传递给 View Composer
- php - Unserialize() 不适用于特定数据