Python/초간단 장고 Django

Django 초간단 게시판 4. view, urls

컴닥 2021. 5. 28. 02:07
반응형

1. view

초간단 버전 답게 모두 클래스 뷰이다. 

리스트뷰를 상속받아 리스트를 만들고, 
디테일뷰를 상속받아 디테일을 만들고...
.....

장고에서는
작성하고, 읽고, 수정하고, 지우는 데 필요한
기본적인 클래스가 모두 제공된다. 

기본적으로 모델만 등록하고
몇 가지 설정만 추가로 잡아주면 된다. 

# board/views.py

from django.urls import reverse_lazy
from django.views.generic import ListView, CreateView, DetailView, UpdateView, DeleteView

from .models import Article


class ArticleList(ListView):
    model = Article
    paginate_by = 5
    ordering = ['-id']


class ArticleCreate(CreateView):
    model = Article
    fields = ['title', 'author', 'content']
    success_url = reverse_lazy('index')


class ArticleDetail(DetailView):
    model = Article
    # context_object_name = 'article'


class ArticleUpdate(UpdateView):
    model = Article
    fields = ['title', 'author', 'content']
    success_url = reverse_lazy('index')


class ArticleDelete(DeleteView):
    model = Article
    success_url = reverse_lazy('index')

리스트 뷰의 필수(?) 요소는 ordering 이다.
설정하지 않아도 작동은 하지만
UnorderedObjectListWarning 경고가 계속 발생한다. 
기본 순서가 없는 모델에서 발생하는 경고. 

page 처리는 직접 처리하기가 꽤 까다롭다.

장고에서는 paginate_by 설정만 해주면,
page 처리가 (템플릿도 꽤 만져줘야 하지만) 가능하다. 
(필수는 아님)

생성과 수정은
에디팅할 필드 설정과 
생성 또는 수정이 끝났을 때 
돌아갈 URL 설정이 필수이다. 

지움도 지움이 성공한 뒤
돌아갈 URL을 설정해야 한다. 

 

2. urls

board 폴더의 urls.py를 수정하자. 

# board/urls.py

from django.urls import path

from .views import ArticleList, ArticleDetail, ArticleDelete, ArticleCreate, ArticleUpdate

urlpatterns = [
    path('', ArticleList.as_view(), name='index'),
    path('create/', ArticleCreate.as_view(), name='create'),
    path('<int:pk>/', ArticleDetail.as_view(), name='detail'),
    path('<int:pk>/update/', ArticleUpdate.as_view(), name='update'),
    path('<int:pk>/delete/', ArticleDelete.as_view(), name='delete'),
]

<int:pk>에서 int를 빼면
create/, admin/과 충돌을 일으킨다. 

int를 명시하면, 숫자는 pk로,
문자는 다른 주소로
교통정리 되기 때문에
충돌을 일으키지 않는다. 

invalid literal for int() with base 10: 'favicon.ico'
이 에러를 처음 봤을 때 황당함이란.. 
왠 favicon.ico인가... 했었다... 

반응형