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에서 매핑
urls.py 안에 필요한 기능을 다 담아주어야 한다. urlpatterns 안에 다음을 추가한다.
(뷰의 설정이나, import방식에 따라 뷰를 불러오는 방식이 달라질 수 있다.)
일반적으로 코드를 짜는 경우 | 제네릭 뷰를 사용하는 경우 |
---|---|
from django.urls import path
from . import views # 해당 앱의 뷰를 불러온다.
app_name = 'board' # 이름공간을 지정.
urlpatterns = [
path('', views.list, name='list'), # list를 보여주는 뷰와 연결한다.
]
|
함수명을 바꾸어주어야 한다.
views.클래스뷰명.as_view()), 형태로. 클래스형 뷰임을 지정해주기 위해. |
3 view 작성
일반적으로 코드를 짤 경우 | 제네릭뷰(클래스형 뷰)를 쓰는 경우 |
---|---|
from django.shortcuts import render
from .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)
|
from django.views import generic
from .models import Question
class ListView(generic.ListView):
def get_queryset(self):
return Question.objects.order_by('-create_date')
#템플릿 명이 명시적으로 지정되지 않은 경우에는 자동으로 모델명_list.html을 템플릿명으로 사용.
|
4 template 작성
board 디렉터리 안에 list.html을 만든다. body 안에 다음을 삽입한다.
일반적으로 코드를 짤 경우 | 제네릭뷰(클래스형 뷰)를 쓰는 경우 |
---|---|
경로에 맞게 해주면 되는데, 위 뷰의 경우엔 /앱이름/template/list.html 에 만들어준다.
만들어진 html파일의 body에 다음과 같이 넣어준다. 상황에 맞게 표를 만들든, 목차를 만들든 html을 짜면 될 터.<body>
<!--뷰에서 writing_list라는 변수에 담은 것들을 반복한다.-->
{% for writing in writing_list %}
{{writing}}</br>
{% endfor %}
</body>
|
템플릿 명이 명시적으로 지정되지 않은 경우에는 자동으로 모델명_list.html을 템플릿명으로 사용. /앱이름/template/question_list.html 을 좌측과 같이 짜주면 된다.
(자동으로 모델명_list라는 이름으로 뷰에서 탬플릿으로 객체를 넘긴다.)#따로 탬플릿 명을 명시하려면 다음의 변수를 get_queryset함수 안에 넣는다.
template='앱이름/list.html'
#탬플릿에 전달될 리스트 이름을 바꾸려면 get_queryset함수 안에 이 변수를 넣는다.
context_object_name='바꿀리스트명'
|
잘 되는 것을 확인했으면 탬플릿을 꾸며보자.
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>