Adding a Custom Column with a Link in Django Admin Changelist
To add a column with a link to http://myservice/{object.id} in the Django admin changelist view, you'll need to customize your ModelAdmin class. Here's how to do it:
Method 1: Using list_display with a custom method
from django.contrib import admin
from django.utils.html import format_html
from django.urls import reverse
@admin.register(YourModel)
class YourModelAdmin(admin.ModelAdmin):
list_display = ('existing_field1', 'existing_field2', 'service_link')
def service_link(self, obj):
url = f"http://myservice/{obj.id}"
return format_html('<a href="{}" target="_blank">View on Service</a>', url)
service_link.short_description = 'Service Link'
Method 2: Using list_display_links if you want it to be clickable like the main field
@admin.register(YourModel)
class YourModelAdmin(admin.ModelAdmin):
list_display = ('existing_field1', 'existing_field2', 'service_link')
list_display_links = ('existing_field1', 'service_link')
def service_link(self, obj):
url = f"http://myservice/{obj.id}"
return format_html('<a href="{}" target="_blank">View on Service</a>', url)
service_link.short_description = 'Service Link'
Method 3: If you want a simple text link without HTML formatting
@admin.register(YourModel)
class YourModelAdmin(admin.ModelAdmin):
list_display = ('existing_field1', 'existing_field2', 'get_service_url')
def get_service_url(self, obj):
return f"http://myservice/{obj.id}"
get_service_url.short_description = 'Service URL'
Important Notes:
- Always use
format_html() when returning HTML to prevent XSS vulnerabilities
- The
target="_blank" opens the link in a new tab (optional)
short_description sets the column header text
- Make sure to include the method name in
list_display
- If you need the link to be sortable, you'll need to implement
get_queryset and annotate the field
Would you like me to explain any part of this in more detail or adapt it to your specific model?