【问题标题】:django admin: how to make a readonly url field clickable in change_form.html?django admin:如何在 change_form.html 中使只读 url 字段可点击?
【发布时间】:2011-07-01 15:02:52
【问题描述】:

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

【问题讨论】:

标签: python django django-admin


【解决方案1】:

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

Ref the doc, readonly_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

上面的代码会在其变更表单页面中呈现三个只读字段。

【讨论】:

  • 这是一个很好的教学例子,应该标记为答案。也许值得一个简短的前言,清楚地表明您正在展示实现同一目标的三种不同方法。但是很棒的东西。谢谢。
【解决方案2】:

我点击了 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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 2012-11-28
      • 2018-07-28
      • 1970-01-01
      • 2014-11-30
      • 1970-01-01
      • 2012-02-01
      • 2010-12-29
      • 2018-06-03
      • 1970-01-01
      相关资源
      最近更新 更多