python - Django 1.4 : return HTML in function

标签 python html django django-1.4

如何在 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_attributemy_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/

相关文章:

python - 删除多个列表中列表的唯一项目

javascript - 通过 jQuery 设置显示属性 - 在 Chrome 中不起作用?

python - Django : Connection refused to live_server_url

python - Django 响应没有内容 - 如何调试?

Django 在反向重定向中使用新创建的对象

从另一个列表中存在的两个列表中查找 2 个项目的 Pythonic 方法

python - 系列'对象没有属性'在 Pandas 中解码

python - 解释Python 3.4下的inspect.getargspec(map)?

javascript - Select2 on change 事件在 Vuejs 中不起作用

javascript - 最小化窗口时标签的文本与文本区域重叠