Django Admin linking to related objects

Modifying your model isn’t necessary, and it’s actually a bad practice (adding admin-specific view-logic into your models? Yuck!) It may not even be possible in some scenarios.

Luckily, it can all be achieved from the ModelAdmin class:

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


class PageAdmin(admin.ModelAdmin):
    # Add it to the list view:
    list_display = ('name', 'user_link', )
    # Add it to the details view:
    readonly_fields = ('user_link',)

    def user_link(self, obj):
        return mark_safe('<a href="https://stackoverflow.com/questions/6418592/{}">{}</a>'.format(
            reverse("admin:auth_user_change", args=(obj.user.pk,)),
            obj.user.email
        ))
    user_link.short_description = 'user'


admin.site.register(Page, PageAdmin)

Edit 2016-01-17:
Updated answer to use make_safe, since allow_tags is now deprecated.

Edit 2019-06-14:
Updated answer to use django.urls, since as of Django 1.10 django.core.urls has been deprecated.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)