繁体   English   中英

使用 django-autocomplete-light v3 自定义项目的 output

[英]Customising the output of items using django-autocomplete-light v3

在 django-autocomplete-light 的早期版本中,您可以使用模板来呈现每个返回的条目,其中包括插入自定义 HTML 的能力

我无法弄清楚如何使用常规 API 来做到这一点,所以我正在尝试添加它。

到目前为止,我有一个像这样的 class,它使用mark_safe并且正在传递 HTML:

class TemplateRenderSelect2QuerySetView(autocomplete.Select2QuerySetView):
    def get_result_label(self, result):
        """Return the label of a result."""
        template = get_template("autocomplete_light/item.html")

        context = Context({"item": result})
        return mark_safe(template.render(context))

模板autocomplete_light/item.html是:

<b>{{ item.name }}</b>

但这被渲染为:

在此处输入图像描述

但是带有正确标签的 JSON 是正确的:

{"pagination": {"more": false}, "results": [{"text": "<b>Victoria</b>", "id": 11}]}

如何让 django-admin 正确呈现 HTML?


编辑:我在自定义 HTML 上找到了一些额外的文档,并尝试针对小部件设置attrs={'data-html': 'true'} ,但它仍然无法正常工作

像往常一样,答案是子类化,在这种情况下,技巧是重写get_result_title

class CustomisableAutocomplete(autocomplete.Select2QuerySetView):
    template_name = "autocomplete_light/item.html"

    def get_result_title(self, result):
        """Return the label of a result."""

        template = get_template(self.template_name)
        context = Context({"result": result})
        return template.render(context)

如果您希望标题不被标签get_results ,则可以覆盖get_results并返回更多数据:

class CustomisableAutocomplete(autocomplete.Select2QuerySetView):
    template_name = "autocomplete_light/item.html"
    def get_result_title(self, result):
        """Return the title of a result."""
        return six.text_type(result)

    def get_result_text(self, result):
        """Return the label of a result."""

        template = get_template(self.template_name)
        context = Context({"result": result})
        return template.render(context)

    def get_results(self, context):
        """Return data for the 'results' key of the response."""
        return [
            {
                'id': self.get_result_value(result),
                'title': self.get_result_title(result),
                'text': self.get_result_text(result),
            } for result in context['object_list']
        ]

'data-html': 文档中的 True 现在可以使用了。

    study = forms.ModelChoiceField(queryset=Study.objects.all(),
                                      widget=autocomplete.ModelSelect2(
                                        url='my_studies-autocomplete',
                                        attrs={
                                            'data-placeholder': 'Please select...',
                                            'data-theme': 'bootstrap4',
                                            'data-html': True
                                        })
                                    )

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM