如何在 Django 1.4 的函数中返回将被解释的 HTML 标记?
class MyModel(models.Model):
my_attribute = models.CharField(max_length=50)
def my_link(self):
return '<a href=google.com>google</a>'
假设我有这个模型,方法是 my_link。在我的管理界面中,我想显示列 my_attribute
和 my_link
。但问题是,html-Tag 不会被解释。它只是打印文本。
从 Django 1.5 开始,django.utils.html
模块中有方法 format_html()
。但我在 Django 1.4 中需要类似的东西
编辑
我的应用程序.admin.py
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
属性:
class MyModel(models.Model):
my_attribute = models.CharField(max_length=50)
def my_link(self):
return '<a href=google.com>google</a>'
my_link.allow_tags = True # <---
根据 ModelAdmin.list_display
documentation :
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.
关于python - Django 1.4 : return HTML in function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21132879/