Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add clickable links to a field in Django admin?

Tags:

python

django

I have this admin.py

class LawyerAdmin(admin.ModelAdmin):
    fieldsets = [
        ('Name',   {'fields': ['last', 'first', 'firm_name', 'firm_url', 'school', 'year_graduated']}),
    ]
    list_display = ('last', 'first', 'school', 'year_graduated', 'firm_name', 'firm_url')
    list_filter = ['school', 'year_graduated']
    search_fields = ['last', 'school', 'firm_name']

and I want to make "firm_url" fields clickable with each of the url listed in the field. How can I do this? Thank you.

like image 954
Zeynel Avatar asked Dec 22 '09 21:12

Zeynel


5 Answers

Use the format_html utility. This will escape any html from parameters and mark the string as safe to use in templates. The allow_tags method attribute has been deprecated in Django 1.9.

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

@admin.display(description="Firm URL")
class LawyerAdmin(admin.ModelAdmin):
    list_display = ['show_firm_url', ...]
    ...

    def show_firm_url(self, obj):
        return format_html("<a href='{url}'>{url}</a>", url=obj.firm_url)
    

Now your admin users are safe even in the case of:

firm_url == 'http://a.aa/<script>eval(...);</script>'

See the documentation for more info.

like image 168
Seppo Erviälä Avatar answered Nov 03 '22 00:11

Seppo Erviälä


Define a custom method in your LawyerAdmin class that returns the link as HTML:

def show_firm_url(self, obj):
    return '<a href="%s">%s</a>' % (obj.firm_url, obj.firm_url)
show_firm_url.allow_tags = True

See the documentation.

like image 69
Daniel Roseman Avatar answered Nov 02 '22 22:11

Daniel Roseman


add show_firm_url to list_display

like image 7
diegueus9 Avatar answered Nov 03 '22 00:11

diegueus9


But it overrides the text display specified in my models and displays "show firm url" on the head of the column

You can change it by assigning short_description property:

show_firm_url.short_description = "Firm URL"
like image 5
Jan Papež - honyczek Avatar answered Nov 03 '22 00:11

Jan Papež - honyczek


You can handle it in the model if you prefer:

In models.py :

class Foo(models.Model):
...


     def full_url(self):
        url = 'http://google.com'
        from django.utils.html import format_html
        return format_html("<a href='%s'>%s</a>" % (url, url))

admin.py:

    list_display = ('full_url', ... )
like image 5
Mesh Avatar answered Nov 02 '22 22:11

Mesh