Django admin:如何使只读url字段在change_form.html中可单击?

2024-04-18 10:04:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我想让一个只读的URL字段在更改表单页面的管理中可以点击。我尝试了一个小部件,但很快意识到小部件只用于表单字段。所以,在我尝试用jQuery(find and replace或其他东西)解决这个问题之前,我想知道python中是否有更优雅的解决方案。有什么想法吗?


Tags: andurl表单部件页面find解决方案jquery
3条回答

更新后的答案可以在this post中找到。

它使用format_htmlutility,因为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"

我遵循了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

老问题,但仍然值得回答。

Ref the docreadonly_fields现在也支持这些自定义方式,工作原理与在注释中发布的the link相同:

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

上述代码将在其更改表单页面中呈现三个只读字段。

相关问题 更多 >