简体   繁体   中英

how to customize django admin panel model columns? django

By saying customize, I don't mean using list_display and things like that.

My meaning of customizing is that I want a column which is not in the model.

The idea is, I want to create a column saying download and there's no such attribute named download in the model. It's just a an url that I want to customize myself which would show up in each row.

an easy example would be something like this in admin page in one of the random models. Let's say this is my Employee model. In my admin page it would show the name of the employee and at the right side I would like to create a download url myself which would export let's say the user's info. I do have the export codes ready and url ready too but I am not sure how to customize it in the admin page.

Model Employee
-------------------------------
name            | download
-------------------------------
Goerge          | download
Fluffy          | download
Techy           | download

Anyone got ideas how this can be done?

Thanks in advance

from django.utils.html import format_html

class EmployeeAdmin(ModelAdmin):
    list_display = ('download', )

    def download(self, obj):
        return format_html('<a href="/your/path/download/{}/">Download</a>', obj.pk)
    download.short_description = 'Download Link'

You can create a function in the "ModelAdmin" subclass that renders custom content in the results table for each entry, like in this answer .

For example, let's say that your "download" text in your table links to a Google search (" https://www.google.com.au/search?q=test "). You can do something like this:

from django.contrib import admin

class EmployeeAdmin(admin.ModelAdmin):
    fields = ('name')
    list_display = ('name', 'download')

    def download(self, obj):
        return '<a href=https://www.google.com.au/search?q="' + obj.name + '">' + obj.name + '</a>'

    download.allow_tags = True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM