Django3 (6. 커텀필드 포매팅) feat.페스트캠퍼스

min seung moon·2021년 3월 30일
0

DJANGO3

목록 보기
6/10

커스텀 필드 포매팅(Product도 커스텀 수정해보기!)

01. product의 admin.py에 재고 추가하고 스타일 주기!

from django.contrib import admin
from .models import Product
from django.utils.html import format_html

# Register your models here.


class ProductAdmin(admin.ModelAdmin):
    list_display = ('name', 'price', 'styled_stock')

    def styled_stock(self, obj):
        if obj.stock <= 50:
            return format_html(f'<span style="color:red">{obj.stock}</span>')
        return format_html(f'<span>{obj.stock}</span>')

    styled_stock.short_description = '재고'


admin.site.register(Product, ProductAdmin)


02. 재고와 가격에 humanize하기!

  • 가격에 humanize하기!
from django.contrib import admin
from .models import Product
from django.utils.html import format_html
from django.contrib.humanize.templatetags.humanize import intcomma

# Register your models here.


class ProductAdmin(admin.ModelAdmin):
    list_display = ('name', 'price_format', 'styled_stock')

    def price_format(self, obj):
        price = intcomma(obj.price)
        return f'{price} 원'

    def styled_stock(self, obj):
        if obj.stock <= 50:
            return format_html(f'<span style="color:red">{obj.stock}</span>')
        return format_html(f'<span>{obj.stock}</span>')

    price_format.short_description = '가격'
    styled_stock.short_description = '재고'


admin.site.register(Product, ProductAdmin)


  • 재고도 humanize하기!
from django.contrib import admin
from .models import Product
from django.utils.html import format_html
from django.contrib.humanize.templatetags.humanize import intcomma

# Register your models here.


class ProductAdmin(admin.ModelAdmin):
    list_display = ('name', 'price_format', 'styled_stock')

    def price_format(self, obj):
        price = intcomma(obj.price)
        return f'{price} 원'

    def styled_stock(self, obj):
        stock = obj.stock
        if stock <= 50:
            stock = intcomma(stock)
            return format_html(f'<b style="color:red">{stock} 개</b>')
        return f'{intcomma(stock)} 개'

    price_format.short_description = '가격'
    styled_stock.short_description = '재고'


admin.site.register(Product, ProductAdmin)


profile
아직까지는 코린이!

0개의 댓글