How to create clickable links for foreign keys in Django admin panel?

Question:

How to make foreign keys clickable in Django admin list view to open related detail admin page?

Currently, Django admin displays foreign keys as plain text in the list view. Is there a way to make these foreign keys clickable links that direct users to the related detail admin page upon clicking? If so, how can this be implemented?

image of Django admin dashboard with foreign key as just a text filed

admin.py

@admin.register(Order)
class OrderAdmin(admin.ModelAdmin):
    ordering = ('pk',)
    list_display = ['pk', 'user', 'order_date', 'deadline', 'status', 'payment', 'total', 'debt', 'shipping']
    list_filter = ['status', 'if_extended']
    exclude = ['order_date', 'deadline', 'return_date', 'total', 'payment', 'shipping', 'if_extended', 'number_of_extensions']
    search_fields = ('pk',)
    inlines = [ItemInline]
Asked By: Tylzan

||

Answers:

Give this a try

from django.urls import reverse
from django.utils.html import format_html

@admin.register(Order)
class OrderAdmin(admin.ModelAdmin):
    ...
    list_display = [
        'pk',
        'user',
        'order_date',
        'deadline',
        'status',
        'payment_link', # changed this 
        'total',
        'debt',
        'shipping',
     ]

    def payment_link(self, obj):
        related_obj = obj.payment
        url = reverse('admin:myapp_payment_change', args=[related_obj.id])  # replace 'myapp' with your app name
        return format_html('<a href="{}">{}</a>', url, related_obj)

    payment_link.short_description = 'Payment'
Answered By: Sumithran
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.