LoginSignup
3
2

More than 5 years have passed since last update.

Django2.0でブログの作成(その2:タイトルと本文の表示)

Posted at

その2

タイトルや本文を表示させよう。

views.py

blog/vies.py
from django.shortcuts import render
from django.utils import timezone
from .models import Post

def post_list(request):
    posts = Post.objects.all()
    return render(request, 'blog/post_list.html', {
        'posts': posts
    })

post_list.html

post_list.html
<html>
    <head>
        <title>my blog</title>
    </head>
    <body>

        {% for post in posts %}
          <div>
              <p>date: {{ post.created_date }}</p>
              <h1><a href="">title: {{ post.title }}</a></h1>
              <p>{{ post.text|linebreaksbr }}</p>
              <hr>
          </div>
        {% endfor %}

    </body>
</html>

created_dateが新しい順に並んでいる秘訣は、
models.pyで class Meta:を設定しているからです。
また、|linebreaksbrは、改行を表示させるという意味です。
pythonでは改行は\nですが、html表示は<br>になるので、その変換処理を行なっているということになります。
フィルタの一覧は以下参照。
Django: 組み込みタグとフィルタの一覧

アクセスして確認

localhost:8000
スクリーンショット 2018-10-09 12.19.59.png

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2