from pybo.models import Question
from django.utils import timezone
for i in range(300):
q = Question(subject="질문글의 제목입니다:[%03d]" % i, content = '내용은 없음', create_date = timezone.now())
q.save()
페이징 기능 구현하기
views.py
javascript로도 가능합니다.
이번엔 django의 Paginator를 활용해서 만들어보겠습니다.
from django.core.paginator import Paginator
def index(request):
page = request.GET.get("page", "1") # 페이지의 번호를 가져옴(그런데 첫 페이지는 1의 기본값 설정)
question_list = Question.objects.order_by('-create_date') # -가 들어가면 내림차순
pagenator = Paginator(question_list, 10) # 페이지 당 10개로 게시글을 제한
page_obj = Paginator.get_page(page) # 전체 페이지에서 요청한 페이지에 관한 게시글만 추출
context = {'question_list' : page_obj} # question_list를 page_obj로 바꾸기
return render(request, 'pybo/question_list.html', context) # request, html 파일, 변수로 담아놨던 question_list
question_list.html
html 내 코드를 이용해서, 밑에 페이지 1,2,3,4,~ 이런식으로 뜨게끔 만들어보겠습니다.
24 - 1 - 3 + 1 = 21 ...................... ... 두번째 페이지
24 - 11 - 0 + 1 = 14
24 - 11 - 1 + 1 = 13 ......
pybo_filter.py 작성 : 장고에는 빼기 연산이 없어서 직접 만들어줘야합니다.
from django import template
register = template.Library()
# A|add:5 --> A에 5를 더한다는 의미
# A|sub:5 --> A가 value 인자가 되고, 뒤에 5가 arg 인자가 됨
@register.filter()
def sub(value, arg):
return value - arg
question_list.html에서 해당 코드를 추가합니다.
{% comment %} - 번호 = 전체 건수 - 시작 인덱스 - 현재 인덱스 + 1 {% endcomment %}
<td>
{{ question_list.paginator.count|sub:question_list.start_index|sub:forloop.counter0|add:1 }}
<td>
질문에 달린 답변 개수 표시하기
question_list.html 파일에 장고 템플릿 언어를 삽입합니다.
<td>
<a href="{% url 'pybo:detail' question.id %}">{{ question.subject }}</a>
{% if question.answer_set.count > 0 %}
<span class = "text-danger small mx-2">{{ question.answer_set.count }}</span>
{% endif %}
</td>
<a> 태그 안에는 question.id를 이용하여 해당 질문의 상세 페이지로 링크를 걸어주고 있습니다.
또한, question.answer_set.count는 해당 질문에 등록된 답변의 개수를 나타냅니다. 이를 이용하여, 해당 질문에 등록된 답변의 개수가 0보다 큰 경우에는 text-danger 클래스를 가진 작은 문자 크기의 HTML 요소를 추가하여 답변 개수를 표시하고 있습니다.
마지막으로, question.create_date는 해당 질문의 작성일을 나타내며, 이를 <td> 태그에 포함하여 표시하고 있습니다.