LoginSignup
3
1

More than 5 years have passed since last update.

Django2.0でブログの作成(その3:記事表示ページ)

Last updated at Posted at 2018-10-09

ページをつくる その3

まだタイトルを押しても飛べないはずです。
移動先の記事ページを作ってリンクを貼りましょう。
記事専用の子ページをarticleとします。

views.py

blog/vies.py
def article(request, pk):
    article = Post.objects.get(id=pk)

    print(article)
    return render(request, 'blog/article.html', {
        'article': article
    })

pkはプライマリーキーです。
記事ごとに順番の番号が振り分けられているのですが、それをarticleでgetしています。
なので、一番最初に投稿した記事にはid=pk=1が入ります。

blog/urls.py

追加します。

blog/urls.py
    path('article/<int:pk>/', views.article, name='article'),

pkは記事の番号でした。

article.html

template/blogの下に記事専用のページを作ります。

article.html
<html>
  <head>
    <!-- bootstrap -->
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
  </head>

  <body>
    <a href="{% url 'blog:post_list' %}" class="btn btn-primary">HOMEへ戻る</a>
    <hr>
    <h1>記事</h1>

    <p>{{ article.title }}</p>
    <p>{{ article.text|linebreaksbr }}</p>
    <hr>
  </body>
</html>

bootstrapを読んでいるので、HOMEへ戻るボタンにclass定義をしてやるとそれっぽくなります。
articleはPost.objectを読んでいました。
なのでarticle.titlearticle.textでタイトルなどが呼び出せます。

リンクの貼り方

<a href="{% url 'blog:post_list' %}">HOMEへ戻る</a>

{% %}でくくります。
リンクなのでurl。
そして、urls.pyで定義したnamespaseを入れ込みます。

課題:ホームのページから記事のページにリンクを貼ってみよう

やってみよー。


【答え】

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="{% url 'blog:article' post.id %}">title: {{ post.title }}</a></h1>
              <p>{{ post.text|linebreaksbr }}</p>
              <hr>
          </div>
        {% endfor %}

    </body>
</html>

"{% url 'blog:article' post.id %}"
記事の番号も渡さないといけないので、 post.id もこの中にいれます!
難しいですね。

3
1
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
1