如何将可点击链接添加到Django管理员中的字段?

Zey*_*nel 54 python django

我有这个admin.py

class LawyerAdmin(admin.ModelAdmin):
    fieldsets = [
        ('Name',   {'fields': ['last', 'first', 'firm_name', 'firm_url', 'school', 'year_graduated']}),
    ]
    list_display = ('last', 'first', 'school', 'year_graduated', 'firm_name', 'firm_url')
    list_filter = ['school', 'year_graduated']
    search_fields = ['last', 'school', 'firm_name']
Run Code Online (Sandbox Code Playgroud)

我想让"firm_url"字段与字段中列出的每个网址一起点击.我怎样才能做到这一点?谢谢.

Sep*_*älä 81

使用该format_html实用程序.这将从参数中转义任何html,并将该字符串标记为在模板中使用是安全的.该allow_tags方法的属性已被弃用,在Django 1.9.

from django.utils.html import format_html

class LawyerAdmin(admin.ModelAdmin):
    list_display = ['show_firm_url', ...]
    ...

    def show_firm_url(self, obj):
        return format_html("<a href='{url}'>{url}</a>", url=obj.firm_url)

    show_firm_url.short_description = "Firm URL"
Run Code Online (Sandbox Code Playgroud)

现在您的管理员用户即使在以下情况下也是安全的:

firm_url == 'http://a.aa/<script>eval(...);</script>'
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅文档.

  • 这应该是选择的答案,因为它可以防止 eval 脚本攻击 (3认同)

Dan*_*man 63

在LawyerAdmin类中定义一个自定义方法,该方法将链接返回为HTML:

def show_firm_url(self, obj):
    return '<a href="%s">%s</a>' % (obj.firm_url, obj.firm_url)
show_firm_url.allow_tags = True
Run Code Online (Sandbox Code Playgroud)

请参阅文档.

  • 请改用[Seppo的回答](http://stackoverflow.com/a/31745953/855050).它更安全. (8认同)
  • 由于django 1.11使用`mark_safe`而不是'allow_tags`,因此不推荐使用 (7认同)
  • 这很容易受到HTML注入的攻击.例如,`obj.firm_url`可能是`http://example.com/<script>alert("I'm evil)); </ script>` (3认同)

die*_*us9 6

添加show_firm_urllist_display


小智 5

但它会覆盖我的模型中指定的文本显示,并在列的顶部显示“显示公司网址”

您可以通过分配short_description属性来更改它:

show_firm_url.short_description = "Firm URL"
Run Code Online (Sandbox Code Playgroud)


Mes*_*esh 5

如果您愿意,可以在模型中处理它:

在 models.py 中:

class Foo(models.Model):
...


     def full_url(self):
        url = 'http://google.com'
        from django.utils.html import format_html
        return format_html("<a href='%s'>%s</a>" % (url, url))
Run Code Online (Sandbox Code Playgroud)

管理.py:

    list_display = ('full_url', ... )
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

38563 次

最近记录:

6 年,3 月 前