0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Django Adminのlist_viewをカスタムしたい

Posted at

ふつう、list_viewの項目はlist_displayで指定される。
以下のように。

class SomeAdmin(admin.ModelAdmin):
    list_display = [
        'some_field_A',
        'some_field_B',
        'some_field_C',
        'some_field_D',
        'some_field_E',
        'some_field_F',
    ]

カスタムしたい時はこう。

class SomeAdmin(admin.ModelAdmin):
    list_display = [
        'some_field_A',
        self.get_custom_display(),
        'some_field_C',
        'some_field_D',
        'some_field_E',
        'some_field_F',
    ]

    def get_custom_display(self, obj):
        return obj.donburi_ippai + "うまい安い早い"

表示は "うまい安い早い"が後ろについた文字列になる。

その場所だけhtmlをカスタムしたいとかは、mark_safe()とかformat_html()を使うとよい。

from django.utils.html import format_html
from django.utils.safestring import mark_safe


class SomeAdmin(admin.ModelAdmin):
    list_display = [
        'some_field_A',
        self.get_custom_html_mark_safe(),
        self.get_custom_html_format_html(),
        'some_field_D',
        'some_field_E',
        'some_field_F',
    ]

    def get_custom_html_mark_safe(self, obj):
        html_string = "<div>丼一つで{}</div>"
        return mark_safe(html_string.format("300年"))

    def get_custom_html_format_html(self, obj):
        html_string = "<div>丼一つで{}</div>"
        return format_html(
            html_string,
            "300年"
        )

どちらも、<div>丼一つで300年</div>が出力される。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?