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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With