简体   繁体   English

如何自定义Django管理面板模型列? 詹戈

[英]how to customize django admin panel model columns? django

By saying customize, I don't mean using list_display and things like that. 说自定义,不是要使用list_display东西。

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. 我的想法是,我想创建一个列为download的列,并且在模型中没有名为download的属性。 It's just a an url that I want to customize myself which would show up in each row. 这只是我要自定义的URL,它将显示在每一行中。

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. 假设这是我的Employee模型。 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. 我确实已经准备好导出代码和url,但是我不确定如何在管理页面中对其进行自定义。

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 . 您可以在“ ModelAdmin”子类中创建一个函数,以在结果表中为每个条目呈现自定义内容,如此答案所示

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 "). 例如,假设您表中的“下载”文本链接到Google搜索(“ 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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