"게시판만들기 2. 게시글 리스트 보기"의 두 판 사이의 차이

Pywiki
둘러보기로 가기 검색하러 가기
잔글 (Sam님이 게시판만들기 2. 게시글 보기 문서를 게시판만들기 2. 게시글 리스트 보기 문서로 이동했습니다)
(차이 없음)

2021년 6월 22일 (화) 20:08 판

1 개요

게시글은 어떻게 띄울 수 있을까? 이번엔 게시글을 보는 방법을 알아보자.

2 url 매핑

2.1 config에서 매핑

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('board/', include('board.urls'))  // board앱으로 처리를 넘긴다.
]

2.2 board.urls에서 매핑

from django.urls import path
from . import views  # 해당 앱의 뷰를 불러온다.

app_name = 'board'  # 이름공간을 지정.

urlpatterns = [
    path('', views.list, name='list'),  # list를 보여주는 뷰와 연결한다.
]

3 view 작성

from django.shortcuts import render
from board.models import Writing  # 모델을 불러온다.

def list(request):
    writing_list = Writing.objects.all()  # 객체들을 다 불러온다.
    writing_list = writing_list.order_by('-create_date')  # 만들어진 시간의 역으로 정렬한다.

    context = {'writing_list':writing_list,  # writing_list라는 키 안에 writing_list를 담는다.
               }
    return render(request, 'board/list.html', context)

4 template 작성

board 디렉터리 안에 list.html을 만든다. body 안에 다음을 삽입한다.

<body>
<!--뷰에서 writing_list라는 변수에 담은 것들을 반복한다.-->
{% for writing in writing_list %}
{{writing}}</br>
{% endfor %}

</body>

잘 되는 것을 확인했으면 탬플릿을 꾸며보자.

5 꾸미기

부트스트랩을 이용해 빠르게 꾸며보도록 하자.

5.1 static 설정

페이지를 꾸미기 위해선 static 파일들이 필수다.

settings.py에서 다음의 옵션을 기입한다.

STATIC_URL = '/static/'  # 처음부터 기입되어 있는 값. 외부에서 접속할 URL 주소.
STATICFILES_DIRS = [ BASE_DIR / 'static', ]  # 프로젝트 전체에서 사용할 정적파일을 탐색할 경로를 넣어준다.(여러개 가능)

5.2 탬플릿에서 부트스트랩 적용

다음 문서를 참고해 부트스트랩을 설치하자.(링크)

head 태그 안에 넣어줘보자.

{% load static %}
<!-- Bootstrap-->
<link rel="stylesheet" type="text/css" href="{% static 'bootstrap/bootstrap.min.css' %}">
<script src="{% static 'bootstrap/bootstrap.min.js' %}"></script>

5.3 탬플릿 작성

body 태그 안에 다음과 같이 표를 작성해준다.

<table class="table table-hover">
    <thead>
    <tr class="table-dark">
        <th>제목</th>
        <th>작성자</th>
        <th>작성일시</th>
    </tr>
    </thead>
    <tbody>
        {% for writing in writing_list %}
        <tr>
        <th>{{writing.subject}}</th>
        <th>{{writing.author}}</th>
        <th>{{writing.create_date}}</th>
        <tr>
        {% endfor %}
    </tbody>
</table>