How to associate another object with a Django admin view?

I created a special admin class to display Admin comments in my Django application. I would like the elements in the "Object ID" section to link to the edit page of objects of the corresponding objects. How can i achieve this?

My admin comments:

class MyCommentsAdmin(admin.ModelAdmin): fieldsets = ( (_('Content'), {'fields': ('user', 'user_name', 'user_email', 'user_url', 'comment')} ), (_('Metadata'), {'fields': ('submit_date', 'ip_address', 'is_public', 'is_removed')} ), ) list_display = ('id', 'name', 'comment', 'content_type', 'object_pk', 'ip_address', 'submit_date', 'is_public', 'is_removed') list_filter = ('submit_date', 'site', 'is_public', 'is_removed') date_hierarchy = 'submit_date' list_display_links = ('id','comment',) ordering = ('-submit_date',) raw_id_fields = ('user',) search_fields = ('comment', 'user__username', 'user_name', 'user_email', 'ip_address') admin.site.unregister(Comment) admin.site.register(Comment, MyCommentsAdmin) 

Thanks!!

+7
source share
1 answer

Define a custom method in the admin class and the link contained in the list_display tuple.

 from django.core.urlresolvers import reverse class MyCommentsAdmin(admin.ModelAdmin): list_display = ('id', 'name', 'comment', 'content_type', 'object_link', 'ip_address', 'submit_date', 'is_public', 'is_removed') list_select_related = True def object_link(self, obj): ct = obj.content_type url = reverse('admin:%s_%s_change' % (ct.app_label, ct.model), args=(obj.id,)) return '<a href="%s">%s</a>' % (url, obj.id) object_link.allow_tags = True 

Note. I added list_select_related=True , since the object_link method refers to the content_type model, so otherwise it would cause the whole load of additional requests to load.

+12
source

All Articles