How do I create clickable text as a URL in Django Admin?

I have a Django REST API app, and I'm trying to create a clickable link from text. So far, I've only found solutions where the URL itself is clickable, and that’s how the current functionality works. However, what I want to achieve is having some text (for example, "ad"), and then having a separate field for the URL. When a user clicks on the text ("ad"), they should be redirected to the URL provided in the other field.

So I have in model this two fields:

 cites = models.CharField(max_length=100, verbose_name="Cites", blank=True)  
 cites_url = models.URLField(max_length=200, verbose_name="Cites URL", blank=True)    

And in admin.py:

from django.utils.html import format_html

class AnimalAdmin(admin.ModelAdmin):
    actions = ['export_to_excel']

    inlines = [AnimalImageInline, AnimalFileInline]
    fields = [
        'cites',
        'cites_url', '
       
    ]
    readonly_fields = ['img_preview', 'klasse_name']
    autocomplete_fields = ['category']

    list_display = ('cites_link')  

    def cites_link(self, obj):
        # Return a clickable link with the text from cites and URL from cites_url
        if obj.cites_url and obj.cites:
            return format_html('<a href="{}" target="_blank">{}</a>', obj.cites_url, obj.cites)
        elif obj.cites_url:
            return format_html('<a href="{}" target="_blank">Click here</a>', obj.cites_url)
        return "No CITES URL provided"

    cites_link.short_description = "CITES Link"

In Django Admin, you can enter text like "ad" in one field and a URL like https://www.ad.nl in another field. However, in the current version, the text "ad" is not clickable.

Question: How can I make the text "ad" clickable, so it links to the URL?

Вернуться на верх