Sander Smits
Sander Smits

Reputation: 2141

django admin: how to make a readonly url field clickable in change_form.html?

I want to make a readonly URL field clickable in the admin on a change_form page. I tried a widget, but soon realized widgets are for form fields only. So, before I try to solve this problem with jQuery (find and replace or something), I would like to know if there is a more elegant solution for this in python. Any ideas?

Upvotes: 25

Views: 12161

Answers (4)

khansahab
khansahab

Reputation: 11

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)

Upvotes: 0

raratiru
raratiru

Reputation: 9616

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"

Upvotes: 19

user2473168
user2473168

Reputation: 141

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

Upvotes: 3

okm
okm

Reputation: 23871

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.

Upvotes: 22

Related Questions