こんにちは。今回も前回に引き続きコメントフォームの機能を作っていきます。
仮想環境の再構築は、こちらをご覧ください。
前回の内容はこちらをご覧ください。
Django:仮想環境再構築後にmigrateする
仮想環境の再構築後は、次の2つのコマンド操作が必要になります。
ターミナルで、次のコマンドを実行します。
$ python manage.py makemigrations
$ python manage.py migrate
この後に、サーバを起動させます。
$ python manage.py runserver
ブラウザで、http://127.0.0.1:8000/にアクセスすると、次のように表示されていると思います。
今回は、コメントを送信した後に、内容を表示する機能を追加します。
Django:views.pyの修正
models.pyのCommentクラスをインポートします。
from tabinou.models import Country, Comment
コメントを5つまで順番に並べます。
comments = Comment.objects.order_by(‘-created_at’)[:5]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
rom django.template.response import TemplateResponse | |
from tabinou.models import Country, Comment | |
from tabinou.forms import CommentForm | |
def index(request): | |
"""メイン画面""" | |
#コメント用フォーム | |
if request.method == 'POST': | |
form = CommentForm(request.POST) | |
if form.is_valid(): | |
# データ追加 | |
form.save() | |
else: | |
form = CommentForm() | |
#タイトル | |
title = 'たびのうのサイト' | |
countrynames = Country.objects.order_by('countryname') | |
comments = Comment.objects.order_by('-created_at')[:5] | |
return TemplateResponse(request, 'tabinou/index.html', | |
{'title': title, | |
'countrynames': countrynames, | |
'comments': comments, | |
'form': form}) |
index.htmlの修正
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<meta charset="UTF-8"> | |
<title>{{ title }}</title> | |
</head> | |
<body> | |
<h1>{{ title }}</h1> | |
<h3>国のデータ</h3> | |
<ul> | |
{% for kuni in countrynames %} | |
<li>{{ kuni.countryname }}: {{ kuni.population }}名</li> | |
{% endfor %} | |
</ul> | |
<form action="/" method="post"> | |
{% csrf_token %} | |
<h3>コメント</h3> | |
{{ form.as_p }} | |
<input type="submit" value="送信"> | |
</form> | |
{% if comments %} | |
<h2>コメント一覧</h2> | |
{% for come in comments %} | |
<h3>{{ come.name }}さんのコメント({{ come.created_at }}):</h3> | |
{{ come.comment|linebreaks }} | |
{% endfor %} | |
{% endif %} | |
</body> | |
</html> |
以上によって、下記のようにコメントを送信すると、内容が表示されるようになったと思います。
いかがでしたでしょうか?今回はフォームからコメントを送信すると、ブラウザに表示される機能を追加しました。
PythonのDJANGOでWEBアプリケーションを構築する方法シリーズは今回で終了です。
ご覧いただきありがとうございました。