SlideShare a Scribd company logo


kay@hannal.net
• 차경묵 (한날)
• 프리랜서 개발자
• 날로 먹는 Django 웹 프로그래밍 (2008)
• 날로 먹는 Django 웹 프레임워크 (2014)
• http://blog.hannal.com
날로 먹는 Django admin 활용
날로 먹는 Django admin 활용
날로 먹는 Django admin 활용


https://www.facebook.com/hello.kaycha

https://github.com/hannal/pieces-of-django-admin-djangogirls-seoul
날로 먹는 Django admin 활용




User
Profile
Product
ProductImage
Order
Profile
class Profile(models.Model):
registration_routes = (
('direct', _(' '), ),
('guestbook', _(' '), ),
('cocoa', _(' '), ),
('goggle', _(' '), ),
('navar', _(' '), ),
)
user = models.OneToOneField(settings.AUTH_USER_MODEL)
registration_route = models.CharField(_(' '), max_length=40,
choices=registration_routes,
default='direct')
Product
class Product(models.Model):
statuses = (
('active', _(' '), ),
('sold_out', _(' '), ),
('obsolete', _(' '), ),
('deactive', _(' '), ),
)
categories = (
('decoration', _(' '), ),
('pan', _(' '), ),
('roll', _(' '), ),
)
category = models.CharField(_(' '), max_length=20, choices=categories)
name = models.CharField(_(' '), max_length=100)
content = models.TextField(_(' '))
regular_price = models.PositiveIntegerField(_(' '))
selling_price = models.PositiveIntegerField(_(' '))
status = models.CharField(_(' '), max_length=20, choices=statuses)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
ProductImage
class ProductImage(models.Model):
product = models.ForeignKey(Product)
content = models.ImageField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
Order
from uuid import uuid4
class Order(models.Model):
progresses = (
('requested', _(' '), ),
('checkout_payment', _(' '), ),
('paid', _(' '), ),
('failed_payment', _(' '), ),
('prepared_product', _(' '), ),
('prepared_delivery', _(' '), ),
('ongoing_delivery', _(' '), ),
('done', _(' '), ),
)
sn = models.UUIDField(_(' '), unique=True, editable=False, default=uuid4)
user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True)
items = models.ManyToManyField(Product)
product_cost = models.IntegerField(_(' '))
progress = models.CharField(_(' '), max_length=20, choices=progresses,
default='requested')
comment = models.TextField(_(' '), null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
날로 먹는 Django admin 활용
from django.contrib import admin
from . import models
admin.site.register(models.Product)
날로 먹는 Django admin 활용
날로 먹는 Django admin 활용
날로 먹는 Django admin 활용
날로 먹는 Django admin 활용
Product object ???
__str__()
__str__()
__str__()
class Product(models.Model):
#
def __str__(self):
return f'<{self.pk}> {self.name}'
날로 먹는 Django admin 활용
날로 먹는 Django admin 활용
list_display
@admin.register(models.Product)
class ProductAdmin(admin.ModelAdmin):
list_display = (
'pk', 'name', 'category', 'regular_price', 'selling_price',
'status', 'created_at', 'updated_at',
)
admin.site.register(models.Product, ProductAdmin)
날로 먹는 Django admin 활용
날로 먹는 Django admin 활용
list_display_links
@admin.register(models.Product)
class ProductAdmin(admin.ModelAdmin):
#
list_display_links = (
'pk', 'name', 'category', 'regular_price', 'selling_price',
'status', 'created_at', 'updated_at',
)
날로 먹는 Django admin 활용
날로 먹는 Django admin 활용
ProductImage
ForeignKey
TabularInline
StackedInline
inlines
class ProductImageInline(admin.TabularInline):
model = models.ProductImage
@admin.register(models.Product)
class ProductAdmin(admin.ModelAdmin):
#
inlines = (ProductImageInline, )
날로 먹는 Django admin 활용




extra
max_num
min_num
class ProductImageInline(admin.TabularInline):
model = models.ProductImage
extra = 2
max_num = 4
min_num = 1
날로 먹는 Django admin 활용
날로 먹는 Django admin 활용
list_filter
search_fields
date_hierarchy
@admin.register(models.Product)
class ProductAdmin(admin.ModelAdmin):
#
list_filter = ('category', 'status', )
search_fields = ('name', 'selling_price', )
date_hierarchy = 'updated_at'
search_fields list_filter
date_hierarchy
날로 먹는 Django admin 활용
short_description
from django.utils.translation import ugettext as _
from django.utils.safestring import mark_safe
@admin.register(models.Product)
class ProductAdmin(admin.ModelAdmin):
list_display = (
'get_title_image', 'pk', 'name', 'category', 'regular_price',
'selling_price', 'status', 'created_at', 'updated_at',
)
list_display_links = (
'get_title_image', 'pk', 'name', 'category', 'regular_price',
'selling_price', 'status', 'created_at', 'updated_at',
)
#
def get_title_image(self, obj):
image = obj.productimage_set.order_by('pk').first()
if not image:
return ''
return mark_safe(f'<img src="{image.content.url}" style="width: 50px;">')
get_title_image.short_description = _(' ')
날로 먹는 Django admin 활용
날로 먹는 Django admin 활용
날로 먹는 Django admin 활용
ForeignKey
fields
readonly_fields
@admin.register(models.Order)
class OrderAdmin(admin.ModelAdmin):
#
readonly_fields = ('user', 'product_cost', 'comment', )
날로 먹는 Django admin 활용
날로 먹는 Django admin 활용
User
User
from django.contrib.auth.models import User
admin.site.unregister(User)
from django.contrib.auth import get_user_model
user_model = get_user_model()
admin.site.unregister(user_model)
User
User
User
UserAdmin
from django.contrib.auth.admin import UserAdmin
@admin.register(user_model)
class CustomUserAdmin(UserAdmin):
list_display = UserAdmin.list_display + ('get_registration_route', )
def get_registration_route(self, obj):
try:
return obj.profile.get_registration_route_display()
except models.Profile.DoesNotExist:
return '?'
get_registration_route.short_description = _(' ')
날로 먹는 Django admin 활용
• User.objects.filter(profile__registration_route='direct')
@admin.register(user_model)
class CustomUserAdmin(UserAdmin):
list_display = UserAdmin.list_display + ('get_registration_route', )
list_filter = UserAdmin.list_filter + ('profile__registration_route', )
def get_registration_route(self, obj):
try:
return obj.profile.get_registration_route_display()
except models.Profile.DoesNotExist:
return '?'
get_registration_route.short_description = _(' ')
날로 먹는 Django admin 활용
날로 먹는 Django admin 활용
admin.SimpleListFilter
lookups() tuple
queryset() QuerySet
QuerySet
from django.db.models import Count, Case, When, IntegerField
class UserOrderCountFilter(admin.SimpleListFilter):
title = _(' ')
parameter_name = 'order_count'
def lookups(self, request, model_admin):
return (
('exact-0', _(' '), ),
('exact-1', _('1 '), ),
('exact-2', _('2 '), ),
('exact-3', _('3 '), ),
('gt-3', _('3 '), ),
)
#
#
def queryset(self, request, queryset):
value = self.value()
if not value:
return queryset
try:
lookup_keyword, count = value.split('-')
count = int(count)
if count == 0:
users = models.Order.objects 
.filter(progress='done') 
.values_list('user__id')
return queryset.exclude(pk__in=users)
else:
return queryset 
.annotate(cnt=Count(Case(
When(order__progress='done', then=0),
output_field=IntegerField()
))).filter(** {f'cnt__{lookup_keyword}': count})
except Exception:
return queryset.none()
@admin.register(user_model)
class CustomUserAdmin(UserAdmin):
list_display = UserAdmin.list_display + (
'get_registration_route',
)
list_filter = UserAdmin.list_filter + (
'profile__registration_route', UserOrderCountFilter,
)
http://.../admin/auth/user/?order_count=exact-1
날로 먹는 Django admin 활용
from django.db.models import Sum
class SumOrderCostFilter(admin.SimpleListFilter):
title = _(' ')
parameter_name = 'order_cost'
def lookups(self, request, model_admin):
return (
('lt-50000', _('5 '), ),
('gte-50000--lt-100000', _('5 10 '), ),
('gte-100000--lt-200000', _('10 20 '), ),
('gte-200000--lt-500000', _('20 50 '), ),
('gte-500000', _('50 '), ),
)
#
def queryset(self, request, queryset):
value = self.value()
if not value:
return queryset
try:
l1, l2 = value.split('--')
except ValueError:
l1, l2 = value, None
lookups = {}
for l in (l1, l2):
if not l:
continue
try:
lookup_keyword, amount = l.split('-')
lookups[f'cost__{lookup_keyword}'] = int(amount)
except ValueError:
continue
#
def queryset(self, request, queryset):
#
#
if not lookups:
return queryset.none()
try:
return queryset.filter(order__progress='done') 
.annotate(cost=Sum('order__product_cost')) 
.filter(**lookups)
except Exception:
return queryset.none()
@admin.register(user_model)
class CustomUserAdmin(UserAdmin):
list_display = UserAdmin.list_display + (
'get_registration_route',
)
list_filter = (
'profile__registration_route',
UserOrderCountFilter, SumOrderCostFilter,
)
http://.../admin/auth/user/?order_cost=lt-50000
날로 먹는 Django admin 활용
actions
queryset
from django.contrib import messages
def change_progress_to_ongoing_delivery(modeladmin, request, queryset):
queryset.update(progress='ongoing_delivery')
messages.success(request, _(' .'))
change_progress_to_ongoing_delivery.short_description = _(' ')
@admin.register(models.Order)
class OrderAdmin(admin.ModelAdmin):
#
actions = (change_progress_to_ongoing_delivery, )
날로 먹는 Django admin 활용
날로 먹는 Django admin 활용
날로 먹는 Django admin 활용
날로 먹는 Django admin 활용
ForeignKey
class ProductOrderInline(admin.StackedInline):
model = models.Order.items.through
min_num = 1
@admin.register(models.Order)
class OrderAdmin(admin.ModelAdmin):
fields = ('progress', )
inlines = (ProductOrderInline, )
templates/admin/<app_name>/<model_name>/
change_list.html
urls.py
• https://github.com/crccheck/django-
object-actions
• pip install django-object-actions
settings.py INSTALLED_APPS
'django_object_actions'
change_list.html
from django_object_actions import DjangoObjectActions
@admin.register(user_model)
class CustomUserAdmin(DjangoObjectActions, UserAdmin):
#
change_actions = ('make_user_happy', )
def make_user_happy(self, request, obj):
messages.info(request, f'{obj} .')
# do something
make_user_happy.label = _(' ')
make_user_happy.short_description = _(' ')
날로 먹는 Django admin 활용
list_max_show_all
@admin.register(user_model)
class CustomUserAdmin(DjangoObjectActions, UserAdmin):
#
list_per_page = 1
list_max_show_all = 1000000
날로 먹는 Django admin 활용

More Related Content

PDF
간단한 블로그를 만들며 Django 이해하기
PDF
Django, 저는 이렇게 씁니다.
PDF
Django admin site 커스텀하여 적극적으로 활용하기
PDF
Celery의 빛과 그림자
PDF
Django로 쇼핑몰 만들자
PDF
Django를 Django답게, Django로 뉴스 사이트 만들기
PDF
Python/Django를 이용한 쇼핑몰 구축(2018 4월 Django Girls Seoul)
PDF
Django in Production
간단한 블로그를 만들며 Django 이해하기
Django, 저는 이렇게 씁니다.
Django admin site 커스텀하여 적극적으로 활용하기
Celery의 빛과 그림자
Django로 쇼핑몰 만들자
Django를 Django답게, Django로 뉴스 사이트 만들기
Python/Django를 이용한 쇼핑몰 구축(2018 4월 Django Girls Seoul)
Django in Production

What's hot (20)

PDF
숨겨진 마이크로서비스: 초고속 응답과 고가용성을 위한 캐시 서비스 디자인
PPTX
Angular
PPTX
Mongo DB 성능최적화 전략
PPSX
Asp.net mvc
PDF
Angular - Chapter 4 - Data and Event Handling
PDF
PyCon KR 2018 Effective Tips for Django ORM in Practice
PDF
이벤트 기반 분산 시스템을 향한 여정
PDF
Vue.js for beginners
PDF
SQL Server에서 Django를 추구하면 안 되는 걸까?
PDF
Naver속도의, 속도에 의한, 속도를 위한 몽고DB (네이버 컨텐츠검색과 몽고DB) [Naver]
PPT
Introduction to Javascript
PDF
2017 Pycon KR - Django/AWS 를 이용한 쇼핑몰 서비스 구축
PPT
Spring AOP
PDF
Massive service basic
PPTX
REST API 설계
PPTX
ASP.NET Web API
PDF
C# Game Server
PDF
Basics of JavaScript
PPTX
Express js
PDF
[수정본] 우아한 객체지향
숨겨진 마이크로서비스: 초고속 응답과 고가용성을 위한 캐시 서비스 디자인
Angular
Mongo DB 성능최적화 전략
Asp.net mvc
Angular - Chapter 4 - Data and Event Handling
PyCon KR 2018 Effective Tips for Django ORM in Practice
이벤트 기반 분산 시스템을 향한 여정
Vue.js for beginners
SQL Server에서 Django를 추구하면 안 되는 걸까?
Naver속도의, 속도에 의한, 속도를 위한 몽고DB (네이버 컨텐츠검색과 몽고DB) [Naver]
Introduction to Javascript
2017 Pycon KR - Django/AWS 를 이용한 쇼핑몰 서비스 구축
Spring AOP
Massive service basic
REST API 설계
ASP.NET Web API
C# Game Server
Basics of JavaScript
Express js
[수정본] 우아한 객체지향
Ad

Similar to 날로 먹는 Django admin 활용 (16)

PPTX
E-Bazaar
PPTX
DJango admin interface
PDF
PDF
Odoo Experience 2018 - Develop an App with the Odoo Framework
PPTX
Develop an App with the Odoo Framework.pptx
PPTX
Session 2 django material for training at baabtra models
PDF
Django design-patterns
PDF
Python Expense Tracker Project with Source Code.pdf
PPTX
Tutorial: Develop an App with the Odoo Framework
PDF
Develop an App with the Odoo Framework
PPTX
Desenvolvimento web usando django
PDF
Django#101 – All You Need to Know for Getting Started
PDF
Deep-dive into Django #1
PDF
Optimization in django orm
KEY
Repensando o Desenvolvimento Web com Ruby on Rails
PDF
Django Good Practices
E-Bazaar
DJango admin interface
Odoo Experience 2018 - Develop an App with the Odoo Framework
Develop an App with the Odoo Framework.pptx
Session 2 django material for training at baabtra models
Django design-patterns
Python Expense Tracker Project with Source Code.pdf
Tutorial: Develop an App with the Odoo Framework
Develop an App with the Odoo Framework
Desenvolvimento web usando django
Django#101 – All You Need to Know for Getting Started
Deep-dive into Django #1
Optimization in django orm
Repensando o Desenvolvimento Web com Ruby on Rails
Django Good Practices
Ad

Recently uploaded (20)

PPTX
Understanding-Communication-Berlos-S-M-C-R-Model.pptx
PPTX
Impressionism_PostImpressionism_Presentation.pptx
PDF
Instagram's Product Secrets Unveiled with this PPT
PPTX
Emphasizing It's Not The End 08 06 2025.pptx
PPTX
Tablets And Capsule Preformulation Of Paracetamol
PDF
Swiggy’s Playbook: UX, Logistics & Monetization
PDF
oil_refinery_presentation_v1 sllfmfls.pdf
PPTX
Hydrogel Based delivery Cancer Treatment
PPTX
Learning-Plan-5-Policies-and-Practices.pptx
PPTX
Primary and secondary sources, and history
PPTX
Effective_Handling_Information_Presentation.pptx
PDF
Why Top Brands Trust Enuncia Global for Language Solutions.pdf
PPTX
Non-Verbal-Communication .mh.pdf_110245_compressed.pptx
PPTX
Presentation for DGJV QMS (PQP)_12.03.2025.pptx
PPTX
INTERNATIONAL LABOUR ORAGNISATION PPT ON SOCIAL SCIENCE
PPTX
Project and change Managment: short video sequences for IBA
PPTX
Tour Presentation Educational Activity.pptx
PPTX
Introduction to Effective Communication.pptx
PPTX
The spiral of silence is a theory in communication and political science that...
PDF
Parts of Speech Prepositions Presentation in Colorful Cute Style_20250724_230...
Understanding-Communication-Berlos-S-M-C-R-Model.pptx
Impressionism_PostImpressionism_Presentation.pptx
Instagram's Product Secrets Unveiled with this PPT
Emphasizing It's Not The End 08 06 2025.pptx
Tablets And Capsule Preformulation Of Paracetamol
Swiggy’s Playbook: UX, Logistics & Monetization
oil_refinery_presentation_v1 sllfmfls.pdf
Hydrogel Based delivery Cancer Treatment
Learning-Plan-5-Policies-and-Practices.pptx
Primary and secondary sources, and history
Effective_Handling_Information_Presentation.pptx
Why Top Brands Trust Enuncia Global for Language Solutions.pdf
Non-Verbal-Communication .mh.pdf_110245_compressed.pptx
Presentation for DGJV QMS (PQP)_12.03.2025.pptx
INTERNATIONAL LABOUR ORAGNISATION PPT ON SOCIAL SCIENCE
Project and change Managment: short video sequences for IBA
Tour Presentation Educational Activity.pptx
Introduction to Effective Communication.pptx
The spiral of silence is a theory in communication and political science that...
Parts of Speech Prepositions Presentation in Colorful Cute Style_20250724_230...

날로 먹는 Django admin 활용