Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django admin list_display_links to foreign key

I am using Django 1.10. In the admin is there an option to set links on Foreign Keys such that when it gets clicked the page is redirected to the Foreign key object.

Admin screen

In the image above StyleID is a foreign key. I would like the Django admin to take me to the corresponding object in the Style table.

like image 358
Dhanushka Amarakoon Avatar asked Mar 15 '17 09:03

Dhanushka Amarakoon


2 Answers

The list_display_links option lets you choose which fields link to the current instance. There isn't an option to make those links point to related instances.

You can create a method on your model admin class that renders a link, then include the method name in your list_display option.

See the Django docs: Reversing admin URLs

from django.contrib import admin
from django.utils.html import format_html

from django.urls import reverse
# Old import:
# from django.core.urlresolvers import reverse

class MyModelAdmin(admin.modelAdmin):
    def style_link(self, obj):
        url = reverse('admin:myapp_style_change', args=(obj.style_id,))
        return format_html("<a href='{}'>{}</a>", url, obj.style_id)
    style_link.admin_order_field = 'style'
    style_link.short_description = 'style'

    list_display = ['widget', 'style_link', ...]

The admin_order_field and short_description attributes are not required, but improve the functionality. See the docs for more information about them.

like image 64
Alasdair Avatar answered Nov 09 '22 20:11

Alasdair


If you are using python3 and wanted to do the same, here are the some modifications to the above :

url = reverse('admin:myapp_style_change', args = [obj.style.id])
return format_html("<a href='{}'>{}</a>", url, obj.style.id)

In place of obj.style.id , you can use whatever field of the model you wanted to display. e.g., return format_html("{}", url, obj.style.name)

like image 44
Aditi Sitoke Avatar answered Nov 09 '22 21:11

Aditi Sitoke