😎
Django開発入門10:詳細ページを追加する2
detail関数を修正する
bbs/views.py
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse
from .models import Article
def index(request):
articles = Article.objects.all()
context = {
'message': 'Welcome my BBS',
'articles': articles,
}
return render(request, 'bbs/index.html', context)
def detail(request, id):
article = get_object_or_404(Article, pk=id)
context = {
'message': 'Show Article ' + str(id),
'article': article,
}
return render(request, 'bbs/detail.html', context)
詳細ページのテンプレートを書く
bbs/templates/bbs/detail.html
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>paiza bbs</title>
<style>body {padding: 10px;}</style>
</head>
<body>
<h1>paiza bbs</h1>
<p>{{ message }}</p>
<p>{{ article.content }}</p>
<p><a href="{% url 'bbs:index' %}">一覧</a></p>
</body>
</html>
一覧ページに詳細ボタンをつける
bbs/templates/bbs/index.html
{% for article in articles %}
<p>
{{ article.content }},
<a href="{% url 'bbs:detail' article.id %}">詳細</a>
</p>
{% endfor %}
Discussion