Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying HTML fields in django admin change list

Is there a way to use HTML in fields in a model's admin's change_list template?

For example: I would like to make the Site domain column clickable, and to be able to navigate to that site:

enter image description here

like image 219
Martin Massera Avatar asked Oct 06 '15 17:10

Martin Massera


People also ask

Where is Django admin?

The django-admin script should be on your system path if you installed Django via pip . If it's not in your path, ensure you have your virtual environment activated. Generally, when working on a single Django project, it's easier to use manage.py than django-admin .

What is the purpose of the admin site in a Django project?

The Django admin application can use your models to automatically build a site area that you can use to create, view, update, and delete records. This can save you a lot of time during development, making it very easy to test your models and get a feel for whether you have the right data.

What is admin panel in Django?

One of the most powerful parts of Django is the automatic admin interface. It reads metadata from your models to provide a quick, model-centric interface where trusted users can manage content on your site. The admin's recommended use is limited to an organization's internal management tool.


2 Answers

You can create a function clickable_site_domain() which returns a HTML link as per the value of site_domain. Then you need to add this method name to the ModelAdmin.list_display attribute. Finally, you need to mark the string safe to avoid HTML escaping with mark_safe.

Prior to Django 1.9, you would need to set allow_tags=True for this function to avoid HTML escaping. (Docs)

from django.utils.text import mark_safe # Older versions
from django.utils.html import mark_safe # Newer versions


class MyModelAdmin(admin.ModelAdmin):

    list_display = (..,'clickable_site_domain', ..) # add the custom method to the list of fields to be displayed.

    def clickable_site_domain(self, obj):
        # return HTML link that will not be escaped
        return mark_safe(
            '<a href="%s">%s</a>' % (obj.site_domain, obj.site_domain)
        )
like image 98
Rahul Gupta Avatar answered Sep 29 '22 22:09

Rahul Gupta


A more recent answer as of 2019 in django 2.2

from django.contrib import admin
from django.utils.html import format_html

@admin.register(MyModel)
class MyModelAdmin(admin.ModelAdmin):
    list_display = [..., 'custom_field', ...]

    def custom_field(self, obj):
        return format_html('<a href={}>URL</a>', obj.url)
like image 42
rowman Avatar answered Sep 30 '22 00:09

rowman