Saturday, October 17, 2009

"View on site" links in list view with Django Admin

The Django admin application has this feature where when you click on an object, if that Model has a "get_absolute_url" method defined, in the corner of the page there will be a link that will go to that object on your site:



This is really handle, but how can I get that link to be put in the list view, so I don't have to click on the object first to get to that link? The answer is to define the following function in the model:


def adminlink(self):
link = self.get_absolute_url()
url = "http://example.com%s" % link
link = "<a href='%s' target='_blank'>Link</a>" % url
return link
adminlink.allow_tags = True


Make sure you include the last line. You must set the function attribute "allow_tags" in order for the admin to not escape the '<' and '>' characters.

The admin declaration, should look like this:


class MyAdmin(admin.ModelAdmin):
list_display = ('user', 'field1', 'field2', MyModel.adminlink)

admin.site.register(MyModel, MyAdmin)


Now when you look at the admin page where it lists all object of MyModel, there should be a new column with your links in it: