Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to link to a different object fom a Django admin view?

I have created a custom admin class to display Comments Admin in my Django app. What I would like to do is for the items under "Object ID" to link to their respective objects' edit object page. How would I achieve that?

My Comments Admin:

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!!

like image 811
rabbid Avatar asked May 04 '11 08:05

rabbid


People also ask

What we can do in admin portal in Django?

Overview. 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.

Can I use Django admin as frontend?

Django Admin is one of the most important tools of Django. It's a full-fledged application with all the utilities a developer need. Django Admin's task is to provide an interface to the admin of the web project. Django's Docs clearly state that Django Admin is not made for frontend work.


1 Answers

This was a good answer but it has changed significantly. This answer is more applicable to Django 3.2.3.

from django.urls import reverse
from django.utils.safestring import mark_safe

class MyCommentsAdmin(admin.ModelAdmin):

    list_display = (
        'id', 'name', 'comment', 'content_type', 'object_link', 'ip_address',
        'submit_date', 'is_public', 'is_removed'
    )

    def object_link(self, obj):
        app_label = obj._meta.app_label
        model_label = obj._meta.model_name
        url = reverse(
            f'admin:{app_label}_{model_label}_change', args=(obj.id,)
        ) 
        return mark_safe(f'<a href="{url}">{obj.id}</a>')
like image 141
tread Avatar answered Sep 25 '22 20:09

tread