如何使用django autocomplete-light在存储的值中添加一些CSS?

时间:2019-05-31 15:05:56

标签: django django-forms django-autocomplete-light

我重写了autocomplete-light的get_results方法,如下所示,以粗体显示了单个标签:

views.py

class TagAutocomplete(autocomplete.Select2QuerySetView):
    def get_queryset(self, **kwargs):
        qs = Tag.objects.all()

        if self.q:
            qs = qs.filter(name__istartswith=self.q)

        return qs


    def get_results(self, context):
        results_list = []
        for result in context["object_list"]:
            text2show = "{}"
            tag_occurrences = result.org_set.count()

            if tag_occurrences == 1:
                text2show = '<b>{}</b>';

            results_list.append({
                "id": self.get_result_value(result),
                "text": format_html(text2show, self.get_result_label(result)),
                "selected_text": format_html(text2show, self.get_selected_result_label(result)),
            })

        return results_list

如果我搜索标签,一切都可以正常工作,但是如果我尝试查看存储的事件,则所有标签均以没有任何样式的方式表示。

forms.py

class EventForm(forms.ModelForm):
    class Meta:
        model = Event
        fields = "__all__" 

        widgets = {
            'tags': autocomplete.ModelSelect2Multiple(url='myapp:tag-autocomplete', attrs={'data-html': True})
        }


    def __init__(self, *args, **kwargs):

        super(EventForm, self).__init__(*args, **kwargs)

        # if I try to edit an event
        if self.instance:

            # self.fields['tag'].queryset = ???

这是我的模板的一部分:

<form method="post" class="form-horizontal">
    {% csrf_token %}
    {% for field in myform %}
    <div class="form-group form-group-lg">
        <label for="{{ field.id_for_label }}" class="col-sm-4 control-label">{{field.label}}</label><div class="col-sm-4">
        {{ field }}
        </div>
    </div>
    {% endfor %}
    {{ myform.media }}
</form> 

有没有一种方法可以操纵 self.fields ['tag']。queryset 查询集,以粗体显示字段名称或其他优雅的解决方案?

谢谢。

更新 models.py

class Tag(models.Model):
    name = models.CharField('Tag name', max_length=255)

    class Meta:
        ordering = ['name']

    def __init__(self, *args, **kwargs):

        return mark_safe("<b>%s</b>" % self.name)

    def __str__(self):
        return self.name

0 个答案:

没有答案