第 9 章    顯示部落格文章

▸ 顯示部落格文章

article/views.py
from django.shortcuts import render

from article.models import Article


def article(request):
    '''
    Render the article page
    '''
    articles = Article.objects.all()
    context = {'articles':articles}
    return render(request, 'article/article.html', context)

▸ 修改範本

article/templates/article/article.html
...
{% block content %}
<br>
{% for article in articles %}
  <h3>{{ article.title }}</h3>
  <p>發表時間:{{ article.pubDateTime|date:'Y-m-d H:i' }}</p>
  <div class="articleContent">{{ article.content }}</div>
  <hr>
{% endfor %}
{% endblock %}

▸ 在 base.html 新增範本區塊

main/templates/main/base.html
...
<head>
<title>部落格</title>
<meta charset="utf-8">
<link rel="stylesheet" href="{% static 'main/css/main.css' %}">
{% block css %}{% endblock %}
</head>
...

▸ 加上樣式

article/static/article/css/article.css
.articleContent {
  padding: 20px;
  background-color: #e9e9e9;
  border: thin solid gray;
  border-radius: 10px;
}

▸ 加上 CSS 連結:

article/templates/article/article.html
{% extends 'main/base.html' %}
{% load static %}
{% block css %}
<link rel="stylesheet" href="{% static 'article/css/article.css' %}">
{% endblock %}
{% block heading %}歡迎蒞臨{% endblock %}
{% block content %}
...
{% endblock %}

▸ 同時取出文章與留言

article/views.py
...
from article.models import Article, Comment


def article(request):
    '''
    Render the article page
    '''
    articles = Article.objects.all()
    articles = {article:Comment.objects.filter(article=article) for article in Article.objects.all()}
    context = {'articles':articles}
    return render(request, 'article/article.html', context)

▸ 頁面顯示文章及留言

article/templates/article/article.html
...
{% block content %}
<br>
{% for article in articles %}
  ...
{% endfor %}
{% for article, comments in articles.items %}
  <h3>{{ article.title }}</h3>
  <p>發表時間:{{ article.pubDateTime|date:'Y-m-d H:i' }}</p>
  <div class="articleContent">{{ article.content|linebreaks|truncatechars_html:30 }}</div>
  {% for comment in comments %}
    <div class="commentDiv">
      <span class="comment">{{ comment.content }}</span>
      <br>
      <span class="commentTime">{{ comment.pubDateTime|date:'m月d日 H:i' }}</span>
    </div>
  {% endfor %}
  <hr>
{% endfor %}
{% endblock %}

▸ 設定樣式

article/static/article/css/article.css
.articleContent {
  ...
}

.commentDiv {
  margin-top: 1em;
}

.comment {
  font-size: 0.8em;
}

.commentTime {
  font-size: 0.6em;
  color: #777777;
}

▸ 本章完成專案:blog9.zip