[Django] DAY18. 백엔드 - 게시판 리스트 로직 : 리스트, 페이징

이하얀·2024년 2월 18일
0

2024년 2월 18일 일요일

📙 강의 내용 요약

  • DBeaver 실행 및 더미 데이터 넣기
    - post 테이블에 새로운 데이터 추가(각 칼럼 내용 삽입)


  • 게시글 내용 보내기 구현

    • 페이지 접속 후, 로그가 나온 것을 알 수 있고, 저장한 21개의 내용이 잘 나오는 것을 알 수 있음.

      # board > views.py
      
      from django.shortcuts import render
      from board.models import Post
      
      def board(request):
          # 게시글 리스트
          if request.method == "GET":
              post_set = Post.objects.all()
      
              print(post_set)
              context = {
                  "title":"안녕 베어유?"
              }
              return render(request, 'page/index.html', context=context)

      # board > views.py
      
      from django.shortcuts import render
      from board.models import Post
      
      def board(request):
          # 게시글 리스트
          if request.method == "GET":
              post_set = Post.objects.all()
      
              context = {
                  "post_set":post_set
              }
              return render(request, 'page/index.html', context=context)
      <!-- templates/page/index.html -->
      
      {% extends 'common/base.html' %}
      
      {% block content %}
          <div class="row">
              {% for post in post_set %}
              <div class="col-6 p-2">
                  <div class="card">
                      <div class="card-body">
                          <h5>제목</h5>
                          <p>내용내용내용내용</p>
                          <p>유저닉네임 <small>12:12:12</small></p>
                          <p>32</p>
                      </div>
                  </div>
              </div>
              {% endfor %}
          </div>
      
          <div class="row mt-4">
              <div class="col-4 text-start">
                  <a class="text-decoration-none fs-5"
                  style="font-weight: bold;color: black;">이전글</a>
              </div>
      
              <div class="col-4 text-center">3/10</a>            
              </div>
      
              <div class="col-4 text-end">
                  <a class="text-decoration-none fs-5"
                  style="font-weight: bold;color: black;">다음글</a>
              </div>
          </div>
      {% endblock %}

  • 실제 데이터베이스 불러오기

...
{% block content %}
<div class="row">
  {% for post in post_set %}
  <div class="col-6 p-2">
    <div class="card">
      <div class="card-body">
        <h5>{{ post.title }}</h5>
        <p>{{ post.content }}</p>
        <p>{{ post.user.nickname }} <small>{{ post.reg_date }}</small></p>
        <p>{{ post.comment_set.all.count }}</p>
      </div>
    </div>
  </div>
  {% endfor %}
</div>
...

  • 에러 발생

    TemplateSyntaxError at /
    'block' tag with name 'content' appears more than once
    
    -> 해결 : {% extends 'common/base.html' %}과
    {% block content %}가 중첩되어 발생한 문제
      
  • 날짜를 Y-m-d 형식으로 출력하기

    ...
    <p>{{ post.user.nickname }} <small>{{ post.reg_date|date:"Y-m-d" }}</small></p>
    ...

  • 게시글 4개씩 페이징하기
    # board>views.py
    
    from django.shortcuts import render
    from board.models import Post
    from django.core.paginator import Paginator
    
    def board(request):
        # 게시글 리스트
        if request.method == "GET":
            page = request.GET.get('page', 1)
            post_set = Post.objects.all().order_by('-id')
            paginator = Paginator(post_set, 4)
    
            post_set = paginator.get_page(page)
    
            context = {
                "post_set":post_set
            }
            return render(request, 'page/index.html', context=context)
  • 이전글, 현재 페이지, 다음글 페이징 사용해서 적용하기
    <!-- index.html -->
    
    ...
    <div class="row mt-4">
                    <div class="col-4 text-start">
                        {% if post_set.has_previous %}
                        <a class="text-decoration-none fs-5"
                        style="font-weight: bold;color: black;"
                        href="{% url 'board' %}?page={{ post_set.previous_page_number }}"
                        >이전글</a>
                        {% endif %}
                    </div>
            
                    <div class="col-4 text-center">
                        {{ post_set.number }}/{{ post_set.paginator.num_pages }}            
                    </div>
            
                    <div class="col-4 text-end">
                        {%if post_set.has_next %}
                        <a class="text-decoration-none fs-5"
                        style="font-weight: bold;color: black;"
                        href="{% url 'board' %}?page={{ post_set.next_page_number }}"
                        >다음글</a>
                        {% endif %}
                    </div>
                </div>
    
            {% endblock %}

♻️ 느낀점&인사이트

오늘 강의는 어제 만든 게시판 리스트 페이지에 맞는 백엔드 로직을 구성하는 강의였다.

먼저 저장된 내용을 잘 불러오는지 테스트하기 위해 더미 데이터를 만들었다.

그 뒤, 게시글과 관련되어 있던 index.html에 {{% %}}를 이용해 반복문으로 게시글 전체를 카드 1개씩 차례대로 불러올 수 있도록 구현했다.

그런데 코드를 복사하고 붙여넣는 과정에서 {% extends 'common/base.html' %} 그리고 {% block content %}를 중복해서 작성하는 바람에 “TemplateSyntaxError at / “가 발생했었다.

다행히 오류가 무엇인지 바로 알아챘고, 해결해서 실제 데이터베이스의 데이터가 불러와지는지 확인을 완료했다.

그리고 django에서 페이징과 관련된 Paginator라는 클래스를 사용해 간단히 한 페이지 내 보여줄 게시글의 개수, 이전글, 다음글, 현재 페이지까지 모두 간단히 가져와 사용할 수 있다는 점이 편리하고 좋았다.

특히, post_set.previous_page_number를 이용하면 이전글 기능을 간단히 활성화할 수 있으며 post_set.next_page_number를 활용하면 다음글 기능을 활성화할 수 있는 점이 좋았다.

profile
언젠가 내 코드로 세상에 기여할 수 있도록, BE 개발 기록 노트☘️

0개의 댓글