关于python:Django 1.4:在函数中返回HTML

Django 1.4: return HTML in function

如何在Django 1.4中的函数中返回将被解释的HTML标记?

1
2
3
4
5
class MyModel(models.Model):
    my_attribute = models.CharField(max_length=50)

    def my_link(self):
        return 'google'

想象一下,我有一个带有my_link方法的模型。在我的管理界面中,我想显示列my_attributemy_link。但是问题是,html-Tag不会被解释。它只是打印文本。

自Django 1.5起,模块django.utils.html中就有方法format_html()。但是我在Django 1.4中需要类似的东西

编辑
myapp.admin.py

1
2
3
4
5
6
7
from django.contrib import admin
from myapp.models import MyModel

class MyModelAdmin(admin.ModelAdmin):
    list_display = ['my_attribute', 'my_link']

admin.site.register(MyModel, MyModelAdmin)

设置allow_tags属性:

1
2
3
4
5
6
class MyModel(models.Model):
    my_attribute = models.CharField(max_length=50)

    def my_link(self):
        return 'google'
    my_link.allow_tags = True # <---

根据ModelAdmin.list_display文档:

If the string given is a method of the model, ModelAdmin or a
callable, Django will HTML-escape the output by default. If you’d
rather not escape the output of the method, give the method an
allow_tags attribute whose value is True. However, to avoid an XSS
vulnerability, you should use format_html() to escape user-provided
inputs.