Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add a custom column with a hyperlink in the django admin interface?

People also ask

Is Django's admin interface customizable if yes then how?

In this article, we will discuss how to enhance Django-admin Interface. Let us create an app called state which has one model with the same name(state). When we register app to admin.py it shows like. Now lets' customize django admin according to available options.

What is Admin Modeladmin in Django?

One of the most powerful parts of Django is the automatic admin interface. It reads metadata from your models to provide a quick, model-centric interface where trusted users can manage content on your site. The admin's recommended use is limited to an organization's internal management tool.

What is Django admin URL?

Start the development web server by executing python manage.py runserver on Django's BASE_DIR . Open a browser on the Django admin site http://127.0.0.1:8000/admin/. You'll see a login screen like the one in Figure 1-5.


Define a method in your ModelAdmin-class and set its allow_tags attribute to True. This will allow the method to return unescaped HTML for display in the column.

Then list it as an entry in the ModelAdmin.list_display attribute.

Example:

class YourModelAdmin(admin.ModelAdmin):
    list_display = ('my_url_field',)

    def my_url_field(self, obj):
        return '<a href="%s%s">%s</a>' % ('http://url-to-prepend.com/', obj.url_field, obj.url_field)
    my_url_field.allow_tags = True
    my_url_field.short_description = 'Column description'

See the documentation for ModelAdmin.list_display for more details.


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

class MyModelAdmin(admin.ModelAdmin):
    list_display = ['show_url', ...]
    ...

    def show_url(self, obj):
        return format_html("<a href='http://pre.com{0}'>{0}</a>", obj.url)

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

url == '<script>eval(...);</script>'

See the documentation for more info.