[Django]-Django admin: how to make a readonly url field clickable in change_form.html?

22๐Ÿ‘

Old question, but still deserves an answer.

Ref the doc,
readonly_fields also supports those customization ways now, works just as the link posted in the comment:

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

The above code would render three readonly fields in its change form page then.

๐Ÿ‘คokm

19๐Ÿ‘

The updated answer can be found in this post.

It uses the format_html utility because allow_tags has been deprecated.

Also the docs for ModelAdmin.readonly_fields are really helpful.

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"
๐Ÿ‘คraratiru

3๐Ÿ‘

I followed the link provided by okm and I managed to include a clickable link in change form page.

My solution (Add to admin.ModelAdmin, NOT 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
๐Ÿ‘คuser2473168

0๐Ÿ‘

in admin.py

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

   class Document(admin.ModelAdmin):
      readonly_fields = ["Document_url"]


      def Document_url(self, obj):
            return format_html("<a target='_blank',href='{url}'>view</a>",url=obj.document_url)
๐Ÿ‘คkhansahab

Leave a comment