django admin make column link
To make a column in Django admin clickable as a link, you can follow these steps:
Define a method in your model admin class that returns the HTML for the link. This method should take an instance of the model as an argument and return a string containing the HTML code for the link.
In the list_display attribute of your model admin class, include the name of the method you just defined. This tells Django admin to display the result of that method as a column in the admin interface.
In the list_display attribute, you can also provide a string that represents the name of the column. This string will be used as the column header in the admin interface.
Optionally, you can define a short_description attribute for the method you created in step 1. This attribute should be a string that represents the desired column header in the admin interface. If you don't provide a short_description attribute, Django will use the name of the method as the column header.
Here's an example:
from django.contrib import admin
from django.utils.html import format_html
from .models import MyModel
class MyModelAdmin(admin.ModelAdmin):
def link_column(self, instance):
# This method returns the HTML code for the link
return format_html('<a href="{}">{}</a>', instance.get_absolute_url(), instance.name)
link_column.short_description = 'Name' # Optional: set the column header
list_display = ('link_column', 'other_column', 'another_column')
admin.site.register(MyModel, MyModelAdmin)
In the example above, the link_column
method returns an HTML link by using the format_html
function provided by Django. It uses the get_absolute_url
method of the model instance to generate the URL for the link. The list_display
attribute includes 'link_column'
to display the link column in the admin interface, along with other columns ('other_column'
and 'another_column'
). The optional short_description
attribute is set to 'Name'
, which will be used as the column header for the link column in the admin interface.