Django admin:如何在change_form.html中让只读URL字段可点击?

25 投票
4 回答
11795 浏览
提问于 2025-04-16 12:15

我想在管理后台的修改表单页面上,让一个只读的URL字段变得可以点击。我试过用小部件,但很快发现小部件只适用于表单字段。所以在我尝试用jQuery(比如查找和替换之类的方式)来解决这个问题之前,我想知道在Python中有没有更优雅的解决方案。有没有什么好主意?

4 个回答

3

我按照okm提供的链接操作,成功在更改表单页面中添加了一个可以点击的链接。

我的解决方案是(添加到admin.ModelAdmin,而不是models.model)

readonly_fields = ('show_url',)
fields = ('show_url',)

def show_url(self, instance):
    return '<a href="%s">%s</a>' % ('ACTUAL_URL' + CUSTOM_VARIABLE, 'URL_DISPLAY_STRING')
show_url.short_description = 'URL_LABEL'
show_url.allow_tags = True
19

更新后的答案可以在 这个帖子 中找到。

它使用了 format_html 这个 工具,因为 allow_tags 已经不再推荐使用了。

另外,关于 ModelAdmin.readonly_fields 的文档也非常有帮助。

from django.utils.html import format_html
from django.contrib import admin

class SomeAdmin(admin.ModelAdmin):
    readonly_fields = ('my_clickable_link',)

    def my_clickable_link(self, instance):
        return format_html(
            '<a href="{0}" target="_blank">{1}</a>',
            instance.<link-field>,
            instance.<link-field>,
        )

    my_clickable_link.short_description = "Click Me"
22

这个问题虽然老了,但还是值得回答。

参考文档readonly_fields 现在也支持这些自定义方式,效果就像评论中提到的这个链接一样:

def the_callable(obj):
    return u'<a href="#">link from the callable for {0}</a>'.format(obj)
the_callable.allow_tags = True

class SomeAdmin(admin.ModelAdmin):
    def the_method_in_modeladmin(self, obj):
         return u'<a href="#">link from the method of modeladmin for {0}</a>'.format(obj)
    the_method_in_modeladmin.allow_tags = True

    readonly_fields = (the_callable, 'the_method_in_modeladmin', 'the_callable_on_object')

ObjModel.the_callable_on_object = lambda self, obj: u'<a href="#">link from the callable of the instance </a>'.format(obj)
ObjModel.the_callable_on_object.__func__.allow_tags = True

上面的代码会在修改表单页面上显示三个只读字段。

撰写回答