はじめてのDjangoアプリ作成(その4)

[ 関連エントリ ]
その1 : プロジェクト作成 & モデル作成
その2 : admin サイトの使い方
その3 : ビュー & テンプレートを作る(照会画面)
その4 : フォームを作る(入力画面)

[ 参考サイト ]
Django ドキュメントはじめての Django アプリ作成、その 4

――――――――

■ 更新処理を記述する。

(01) ファイル「views.py」を編集。URLアクセス時の動作を記述する。

from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from mysite.polls.models import Choice, Poll
 
def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html',
                              {'latest_poll_list': latest_poll_list})
 
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})
 
def vote(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    try:
        selected_choice = p.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        # Poll 投票フォームを再表示します。
        return render_to_response('polls/detail.html', {
            'poll': p,
            'error_message': "選択肢を選んでいません。",
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        # ユーザが Back ボタンを押して同じフォームを提出するのを防ぐ
        # ため、POST データを処理できた場合には、必ず
        # HttpResponseRedirect を返すようにします。
        return HttpResponseRedirect(reverse('mysite.polls.views.results', args=(p.id,)))
 
def results(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/results.html', {'poll': p})

(02) ファイル「detail.html」を編集。

<h1>{{ poll.question }}</h1>
 
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
 
<form action="/polls/{{ poll.id }}/vote/" method="post">
{% for choice in poll.choice_set.all %}
    <input type="radio" name="choice" id="choice{{ forloop.counter }}"
     value="{{ choice.id }}" />
    <label for="choice{{ forloop.counter }}">{{ choice.choice }}</label><br />
{% endfor %}
<input type="submit" value="投票する" />
</form>

(03) ファイル「results.html」を作成。テンプレートフォルダ配下に配置する。

<h1>{{ poll.question }}</h1>
 
<ul>
{% for choice in poll.choice_set.all %}
    <li>{{ choice.choice }} -- {{ choice.votes }} 票</li>
{% endfor %}
</ul>

(04) ブラウザにて「http://localhost:8000/polls/[存在するpoll_id]/」にアクセス。ラジオボタンの表示を確認。

(05) 「投票」押下にて、画面遷移することを確認。
 

(06) SQL文にて、正しくデータが反映されていることを確認。

    select * from polls_choice;
    +―-+―――+―――――+――-+
    | id | poll_id | choice | votes |
    +―-+―――+―――――+――-+
    | 1 | 2 | sentaku-shi 1 | 2 |
    | 2 | 2 | sentaku-shi 2 | 0 |
    | 3 | 2 | sentaku-shi 3 | 0 |
    +―-+―――+―――――+――-+

※ 「UnicodeDecodeError」が表示されて、しばらく迷いましたが
  テンプレートHTMLの文字コードが「Shift-JIS」になってました。「UTF-8」に修正。