Custom html field in django admin changelist_view

I would like to tweak a bit using django admin, especially changelist_view

 class FeatureAdmin(admin.ModelAdmin): list_display = ( 'content_object_change_url', 'content_object', 'content_type', 'active', 'ordering', 'is_published', ) list_editable = ( 'active', 'ordering', ) list_display_links = ( 'content_object_change_url', ) admin.site.register(get_model('features', 'feature'), FeatureAdmin) 

The idea is that 'content_object_change_url' can be a reference to another change_view ... convenience for the admin user to quickly jump directly to the element.

In another case, I would like this to add links to external sources or thumbnails of image fields.

I thought I heard about the "insert html" option, but maybe I overtook myself.

Thank you for your help!

+4
source share
3 answers

You can provide your own method in the FeatureAdmin class that returns HTML for content_object_change_url :

 class FeatureAdmin(admin.ModelAdmin): [...] def content_object_change_url(self, obj): return '<a href="%s">Click to change</a>' % obj.get_absolute_url() content_object_change_url.allow_tags=True 

See the documentation .

+11
source

Please note and use format_html (see docs here ) as mark_safe util is deprecated since version 1.10. In addition, support for the allow_tags attribute of ModelAdmin methods will be removed from version 1.11.

 from django.utils.html import format_html from django.contrib import admin class FeatureAdmin(admin.ModelAdmin): list_display = ( 'change_url', [...] ) def change_url(self, obj): return format_html('<a target="_blank" href="{}">Change</a>', obj.get_absolute_url()) change_url.short_description='URL' 
+1
source

It took me two hours to figure out why Daniel Roseman's solution did not work for me. Despite the fact that he is right, there is one exception: when you want to create your own calculated fields (read-only) in Admin . This will not work. A very simple solution (but hard to find) is to return the string to a special constructor: SafeText() . Perhaps this is due to Django 2 or readonly_fields (which behave differently than the classic ones)

Here's a working sample that works, but not without SafeText() :

 from django.utils.safestring import SafeText class ModelAdminWithData(admin.ModelAdmin): def decrypt_bin_as_json(self, obj): if not obj: return _("Mode insert, nothing to display") if not obj.data: return _("No data in the game yet") total = '<br/><pre>{}</pre>'.format( json.dumps(json.loads(obj.data), indent=4).replace(' ', '&nbsp;')) return SafeText(total) # !! working solution !! <------------------ decrypt_bin_as_json.short_description = _("Data") decrypt_bin_as_json.allow_tags = True readonly_fields = ('decrypt_bin_as_json',) fieldsets = ( (_('Data dump'), { 'classes': ('collapse',), 'fields': ('decrypt_bin_as_json',) }), ) 
0
source

All Articles