How to add clickable links to a field in Django admin?
Solution 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
@admin.display(description="Firm URL")
class LawyerAdmin(admin.ModelAdmin):
list_display = ['show_firm_url', ...]
...
def show_firm_url(self, obj):
return format_html("<a href='{url}'>{url}</a>", url=obj.firm_url)
Now your admin users are safe even in the case of:
firm_url == 'http://a.aa/<script>eval(...);</script>'
See the documentation for more info.
Solution 2:
Define a custom method in your LawyerAdmin class that returns the link as HTML:
def show_firm_url(self, obj):
return '<a href="%s">%s</a>' % (obj.firm_url, obj.firm_url)
show_firm_url.allow_tags = True
See the documentation.
Solution 3:
add show_firm_url
to list_display
Solution 4:
You can handle it in the model if you prefer:
In models.py :
class Foo(models.Model):
...
def full_url(self):
url = 'http://google.com'
from django.utils.html import format_html
return format_html("<a href='%s'>%s</a>" % (url, url))
admin.py:
list_display = ('full_url', ... )