How to add custom hyperlink column to django admin interface?

I have a django admin interface, and in the model listing I want to create my own column, which will be a hyperlink using one of the field values. Basically, one of the model fields is a URL, and I would like the column to have that URL in an interactive hyperlink. This link must have an additional URL added to it as a relative path in the model field.

+46
django django-admin
Jan 28 '10 at 16:33
source share
2 answers

Define a method in your ModelAdmin class and set its allow_tags attribute to True . This will allow the method to return unshielded 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' 

See the documentation for ModelAdmin.list_display for more details .

+60
Jan 28
source share
β€” -

Use the format_html utility. This will avoid any html from the parameters and mark the line as safe for use in templates. The allow_tags method allow_tags deprecated in Django 1.9.

 from django.utils.html import format_html class MyModelAdmin(admin.ModelAdmin): list_display = ['show_url', ...] ... def show_url(self, obj): return format_html("<a href='http://pre.com{0}'>{0}</a>", obj.url) 

Now your admin users are safe even in the case of:

 url == '<script>eval(...);</script>' 

See the documentation for more details.

+7
Jul 31 '15 at 12:23
source share



All Articles