I'm trying to add a "View on site" link to my list_display in Django Admin.
This seems like a pretty common use case, is there a shortcut way of doing it?
You could write a reusable mixin like this (untested):
class ViewOnSiteMixin(object):
def view_on_site(self, obj):
return mark_safe(u"<a href='%s'>view on site</a>" % obj.get_absolute_url())
view_on_site.allow_tags = True
view_on_site.short_description = u"View on site"
Use it like this:
class SomeAdmin(ViewOnSiteMixin, admin.ModelAdmin):
list_display = [..., "view_on_site", ...]
(of course needs get_absolute_url
defined on your model)
Using view_on_site will muck up the "View on site" link within the admin view - that link shows up when you set get_absolute_url for your model.
Instead you can use just about any other name for that column, just match it with the function name.
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _
class ServisAdmin(admin.ModelAdmin):
list_display = (.. ,'view_link')
def view_link(self, obj):
return mark_safe(
'<a href="{0}">{1}</a>'.format(
obj.get_absolute_url(),
_("View on site")
)
)
view_link.allow_tags = True
view_link.short_description = _("View on site")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With