tags:

views:

121

answers:

1

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.

+4  A: 

Define a method in your ModelAdmin-class and set its allow_tags attribute to True. This will allow the method to return unescaped HTML for display in the column.

Then list it as an entry in the ModelAdmin.list_display attribute.

Example:

class YourModelAdmin(admin.ModelAdmin):
    list_display = ('my_url_field',)

    def my_url_field(self, obj):
        return '<a href="%s%s">%s</a>' % ('http://url-to-prepend.com/', obj.url_field, obj.url_field)
    my_url_field.allow_tags = True
    my_url_field.short_description = 'Column description'

Se the documentation for ModelAdmin.list_display for more details.

drmegahertz
I found out the other day that you actually don't need the `a` tag, since Django admin will automatically turn the URL into a hyperlink. I'm not at my work PC though, so I could be wrong. In my case, I didn't need to set `allow_tags`. I also created a `get_url()` function on my model, as opposed to my admin model - but that's fairly trivial. However, your way is best if we want to open the link in a new window with `target=_blank` -- Hope this is helpful.
nbolton