Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
162 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...