Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a "View on Site" link to the Django admin list_display

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?

like image 504
John Carter Avatar asked Feb 12 '23 19:02

John Carter


2 Answers

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)

like image 57
sk1p Avatar answered Feb 16 '23 12:02

sk1p


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")
like image 20
MarZab Avatar answered Feb 16 '23 10:02

MarZab