티스토리 뷰

  ● 게시물 목록  

 

post/views.py

- 게시물 목록 관련 로직은 Post 객체를 모두 받아온 것을 html로 보내 나타낸다.

- 최신순으로 정렬한 게시물들을 posts에 저장하고 'post_list.html'와 같이 렌더링한다. 

def post_list(request):
    posts = Post.objects.order_by('-created_at')
    return render(request, 'post_list.html', context = {'posts':posts})

 

 

 

templates/post_list.html

- 역시 html은 어렵다. 좀 더 블로그스럽게 css를 변경했다. 이번에는 테이블에서 글 목록을 정렬하는 방식아니라 텍스트 형식으로 나타낸다. 

- a 태그를 사용하여 post-title 이나 post-subtitle을 클릭했을 때 해당 게시물의 상세보기 페이지로 이동하도록 한다.

- 제목과 내용을 표시하는데 truncatechars 를 사용하여 지정된 문자 수보다 긴 문자열은 잘라내서 "...." 으로 나타낸다

- 작성자와 작성 시간을 아랫줄에 나타낸다.

{% extends 'base_.html' %}
{% block content %}
<div class = "container">
    {% for post in posts %}
        <div class = "col-lg-8 col-md-10 mx-auto">
            <div class "post-preview">
                <a href = "{% url 'post_detail' post.id %}">
                    <h2 class = "post-title">
                        {{post.title}}
                    </h2>
                    <h3 class = "post-subtitle">
                        {{post.content | truncatechars:10}}
                    </h3>
                </a>
                <p class = "post-meta">Posted by
                    <a href = "#">{{post.user}}</a>
                {{post.created_at}}</p>
            </div>
        </div>
    {% endfor %}
    <div class = "row">
        <div class = "col-lg-8 col-md-10 mx-auto">
            <a href = "{% url 'post_write' %}" class = "btn btn-primary float-right">글쓰기</a>
        </div>
    </div>
</div>
{% endblock %}

 

 

 

 

실행 결과

댓글