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

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.



Solution 1:[1]

Use the format_html utility. This will escape any html from parameters and mark the string as safe to use in templates. The allow_tags method attribute has been deprecated in Django 1.9.

from django.utils.html import format_html
from django.contrib import admin
from django.utils.translation import gettext_lazy as _

class MyModelAdmin(admin.ModelAdmin):
    list_display = ['show_url', ...]
    # ...

    @admin.display(description=_("Column title"))
    def show_url(self, obj):
        return format_html("<a href='http://pre.com{0}'>{0}</a>", obj.url)

Now your admin users are safe even in the case of:

url == '<script>eval(...);</script>'

See the documentation for more info.

Solution 2:[2]

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'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Flimm
Solution 2 Alex Winkler