바뀜

2,205 바이트 추가됨 ,  2021년 6월 25일 (금) 12:48
18번째 줄: 18번째 줄:     
=== board.urls에서 매핑 ===
 
=== board.urls에서 매핑 ===
<syntaxhighlight lang="python">
+
urls.py 안에 필요한 기능을 다 담아주어야 한다. urlpatterns 안에 다음을 추가한다.
 +
 
 +
(뷰의 설정이나, import방식에 따라 뷰를 불러오는 방식이 달라질 수 있다.)
 +
{| class="wikitable"
 +
!일반적으로 코드를 짜는 경우
 +
!제네릭 뷰를 사용하는 경우
 +
|-
 +
|<syntaxhighlight lang="python">
 
from django.urls import path
 
from django.urls import path
 
from . import views  # 해당 앱의 뷰를 불러온다.
 
from . import views  # 해당 앱의 뷰를 불러온다.
28번째 줄: 35번째 줄:  
]
 
]
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
|함수명을 바꾸어주어야 한다.
 +
views.클래스뷰명.as_view()), 형태로.
    +
클래스형 뷰임을 지정해주기 위해.
 +
|}
 
== view 작성 ==
 
== view 작성 ==
<syntaxhighlight lang="python">
+
{| class="wikitable"
 +
! 일반적으로 코드를 짤 경우
 +
!제네릭뷰(클래스형 뷰)를 쓰는 경우
 +
|-
 +
|<syntaxhighlight lang="python">
 
from django.shortcuts import render
 
from django.shortcuts import render
from board.models import Writing  # 모델을 불러온다.
+
from .models import Writing  # 모델을 불러온다.
    
def list(request):
 
def list(request):
42번째 줄: 57번째 줄:  
     return render(request, 'board/list.html', context)
 
     return render(request, 'board/list.html', context)
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
|<syntaxhighlight lang="python">
 +
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을 템플릿명으로 사용.
 +
 +
</syntaxhighlight>이미 만들어진 기능을 사용하는 것이기에, 짧게 구성된다.
 +
|}
 
== template 작성 ==
 
== template 작성 ==
board 디렉터리 안에 list.html을 만든다. body 안에 다음을 삽입한다.<syntaxhighlight lang="html">
+
 
 +
board 디렉터리 안에 list.html을 만든다. body 안에 다음을 삽입한다.
 +
{| class="wikitable"
 +
! 일반적으로 코드를 짤 경우
 +
!제네릭뷰(클래스형 뷰)를 쓰는 경우
 +
|-
 +
|경로에 맞게 해주면 되는데, 위 뷰의 경우엔 /앱이름/template/list.html 에 만들어준다.
 +
만들어진 html파일의 body에 다음과 같이 넣어준다.
 +
상황에 맞게 표를 만들든, 목차를 만들든 html을 짜면 될 터.<syntaxhighlight lang="html">
 
<body>
 
<body>
 
<!--뷰에서 writing_list라는 변수에 담은 것들을 반복한다.-->
 
<!--뷰에서 writing_list라는 변수에 담은 것들을 반복한다.-->
52번째 줄: 85번째 줄:     
</body>
 
</body>
</syntaxhighlight>잘 되는 것을 확인했으면 탬플릿을 꾸며보자.
+
</syntaxhighlight>
 +
|템플릿 명이 명시적으로 지정되지 않은 경우에는 자동으로 모델명_list.html을 템플릿명으로 사용. /앱이름/template/question_list.html 을 좌측과 같이 짜주면 된다.
 +
(자동으로 모델명_list라는 이름으로 뷰에서 탬플릿으로 객체를 넘긴다.)<syntaxhighlight lang="python">
 +
#따로 탬플릿 명을 명시하려면 다음의 변수를 get_queryset함수 안에 넣는다.
 +
        template='앱이름/list.html'
 +
</syntaxhighlight>탬플릿에 전달되는 리스트는 question_list라는 이름이었는데, 전달할 이름을 바꾸려면 다음과 같이 넣어준다.<syntaxhighlight lang="python">
 +
#탬플릿에 전달될 리스트 이름을 바꾸려면 get_queryset함수 안에 이 변수를 넣는다.
 +
    context_object_name='바꿀리스트명'
 +
</syntaxhighlight>
 +
|}잘 되는 것을 확인했으면 탬플릿을 꾸며보자.
    
= 꾸미기 =
 
= 꾸미기 =