如何防止Django在ModelAdmin中转义HTML

时间:2011-11-03 11:35:16

标签: python django django-admin

我有这个课程为我的django.contrib.admin模型配置Stream

class StreamAdmin(admin.ModelAdmin):
    def stream_title(instance):
        return instance.info.title

    def network_name(instance):
        return '<img src="%s" />' % instance.network.image_url

    fieldsets = (
        (None, {
            'fields' : ('name', 'network', 'score', 'custom_url')
        }),

    )

    list_display = ('name', stream_title, network_name, 'online', 'score')

    ordering = ('name', 'score')

network_name函数返回HTML,但它已被转义。我怎么能阻止它?

2 个答案:

答案 0 :(得分:5)

使用allow_tags

def network_name(instance):
    return '<img src="%s" />' % instance.network.image_url
network_name.allow_tags = True

答案 1 :(得分:2)

您可以使用mark_safe

from django.utils.safestring import mark_safe

class StreamAdmin(admin.ModelAdmin):
    ...

    def network_name(instance):
        return mark_safe('<img src="%s" />' % instance.network.image_url)

    ...

尝试在模板上使用safe过滤器,甚至autoescape

使用autoescape标签可以设置如下块:

{% autoescape on %}
    {{ model.network_name }}
{% endautoescape %}

<!-- or either -->
{{ model.network_name|safe }}