Milano
Milano

Reputation: 18725

Django admin changelist - link to related model change page

Is there a built-in way to tell Django to show links to related models in changelist?

If we have models School and Student, I want display School in Student changelist as a link to School object change page.

I can do that old way:

class StudentAdmin(..):
    list_display = [...,'school',...]

    def school(..):
        return mark_safe(..link..)

Is there a built in way? Something like:

class StudentAdmin(..):
    ...
    related_change_links = ['school']

Upvotes: 1

Views: 2021

Answers (2)

dirkgroten
dirkgroten

Reputation: 20682

No there isn't a built-in way. Defining your own read-only field for it, as you show in your question, is the right way to do it.

You could try to subclass ModelAdmin to add your own related_change_links property, if you want to use that in many places. That would entail overriding the __init__ function to add the fields to read_only_fields and overriding __getattr__ to dynamically create the getters for these fields.

Upvotes: 0

Higor Rossato
Higor Rossato

Reputation: 2046

If you want something custom I believe that's the most pythonic way of doing that. Otherwise I guess that this should solve your issue.

from django.utils.html import format_html


def school(self, instance):
    school_id = instance.school.pk
    info = (School._meta.app_label, School._meta.model_name)
    url = reverse('admin:{}_{}_change'.format(*info), args=(school_id,))

    return format_html('<a href="{url}">{text}</a>'.format(
        url=url,
        text=school_id))

Upvotes: 2

Related Questions