환경
- Ubuntu Server 22.04
- VSCode Insider
- Remote SSH Extension
- Python 3.10 venv
- Django 5.1.1
- SQLite 3.37.2
준비
source django_env/bin/activate
실행
admin.py (Custom admin page)
# polls/admin.py
# The no-hassle way
# admin.site.register(Question)
# admin.site.register(Choice) # not needed anymore cuz inline
# 질문 편집 페이지 내에 초이스 편집 기능 생성
class ChoiceInline(admin.TabularInline): # StackedInline도 있음
# these too, are implicit
model = Choice
extra = 3 # 디폴트 입력창 개수
# custom admin page : replaces the above defaults
class QuestionAdmin(admin.ModelAdmin):
# ModelAdmin 클래스 내장 변수인듯
fieldsets = [
# 필드셋 순서에 따라 admin페이지에서 순서도 바뀜
('Question', {'fields': ['question_text']}), # 이 부분이 None이었음
# collapsable로 만들 수 도 있다
('Published date', {'fields': ['pub_date'], 'classes': ['collapse']}),
]
# 필드 목록 표시 방법 (overrides def __str__ in models.py)
list_display = ('question_text', 'pub_date', 'is_recent') # 커스텀 메소드도 가능
# 필드 속성 읽기전용으로
readonly_fields = ['pub_date']
# inline style sub-fields
inlines = [ChoiceInline]
# filter rule sticks to the attrib data type
list_filter = ['pub_date']
# keyword search option: attrib data type
search_fields = ['question_text', 'choice__choice_text'] # sub-field criteria: django syntax
admin.site.register(Question, QuestionAdmin)
models.py
from django.db import models
from django.contrib import admin
from django.utils import timezone
import datetime
class Question(models.Model):
# verbose name for admin page column name
question_text = models.CharField(max_length=200, verbose_name='Question')
pub_date = models.DateTimeField(auto_now_add=True, verbose_name='Published On')
# verbose column for a custom method
@admin.display(boolean=True, description='Recenlt Post') # boolean is for checkbox icon
def is_recent(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
def __str__(self):
if self.is_recent():
badge = 'NEW'
else:
badge = ''
return f'{badge} [title: {self.question_text}] [date: {self.pub_date}]'
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return f'[{self.question.question_text}] {self.choice_text}'
CRUD is short for Crush, Ruin, Undermine and Destroy
'W | eb' 카테고리의 다른 글
Django CRUD: API (0) | 2024.10.09 |
---|---|
Django CRUD: Serialize (0) | 2024.10.08 |
Django Template (0) | 2024.10.08 |
Django MVC(MTV) (0) | 2024.10.07 |
HTML (0) | 2024.10.02 |