How do I add a custom column with a hyperlink in the django admin interface?

Viewed 34470

I have a django admin interface and in the model listing I want a custom column that will be a hyperlink using one of the fields values. Basically one of the models' fields is a url and i'd like the column to have that URL in a clickable hyperlink. This link will need to have additional URL prepended to it as its a relative path in the model field.

3 Answers

Define a method in your ModelAdmin-class and set its allow_tags attribute to True. This will allow the method to return unescaped HTML for display in the column.

Then list it as an entry in the ModelAdmin.list_display attribute.

Example:

class YourModelAdmin(admin.ModelAdmin):
    list_display = ('my_url_field',)

    def my_url_field(self, obj):
        return '<a href="%s%s">%s</a>' % ('http://url-to-prepend.com/', obj.url_field, obj.url_field)
    my_url_field.allow_tags = True
    my_url_field.short_description = 'Column description'

See the documentation for ModelAdmin.list_display for more details.

I am using 'instance' instead of 'obj'. Seppo Erviälä's answer helped me the most as I'm using Django 3.0.1.

def get_facebook(self, instance):
    return format_html("<a target='_blank' href='{0}'>{0}</a>", instance.profile.facebook)
get_facebook.short_description = 'Facebook'
Related