首页 > 解决方案 > Django Taggit - 自动完成灯(配置指南)

问题描述

我已经完全启动并运行了 Taggit,并且想要配置 Autocomplete Light,以便在用户在我的应用程序中选择他们喜欢的标签时启用 Select2 下拉菜单。

我已经安装了DALdal_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 的文档,但我不太确定从我已有的代码中去哪里。

任何指导将不胜感激!

谢谢!:-)

标签: pythondjangodjango-autocomplete-lightdjango-taggit

解决方案


尝试将此代码添加到您拥有表单的 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>

之后,下拉菜单应该可以工作。更多细节在这里


推荐阅读