2013-10-20

Python初心者がDjangoチュートリアルを触ってみる(Part 4)

今回はフォーム画面の作成。

チュートリアルだとvoteだけだったので、Pollの新規作成画面も作成してみた。

チュートリアルとの差分はurls.py, newpoll.html, index.htmlあたり。

 

polls/urls.py

from django.conf.urls import patterns, url
from polls import views

urlpatterns = patterns('',
    # ex: /
    url(r'^$', views.IndexView.as_view(), name='index'),
    # ex: /polls/5/
    url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'),
    # ex: /polls/5/results/
    url(r'^(?P<pk>\d+)/results/$', views.ResultsView.as_view(), name='results'),
    # ex: /polls/5/vote/
    url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote'),
    # ex: /polls/new/
    url(r'^new/$', views.newpollview, name='newpoll'),
    # ex: /polls/newpost/
    url(r'^newpost/$', views.newpollpost, name='newpollpost'),
    # ex: /polls/deletepoll
    url(r'^(?P<poll_id>\d+)/delete/$', views.deletepoll, name='deletepoll'),
)

 

polls/views.py

from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext, loader
from django.shortcuts import render, get_object_or_404
from django.core.urlresolvers import reverse
from django.views import generic
from polls.models import Poll, Choice

#genericモジュールを使用しないバージョン
def index(request):
    #pub_dateが最新のPollオブジェクトを取得
    latest_poll_list = Poll.objects.order_by('-pub_date')[:5]

    #ショートカットを使わない場合
    """
    template = loader.get_template('polls/index.html')
    context = RequestContext(request, {
        'latest_poll_list' : latest_poll_list,
    })
    return HttpResponse(template.render(context))
    """

    #テンプレートにバインディングして表示
    context = {
        'latest_poll_list' : latest_poll_list,
    }
    return render(request, 'polls/index.html', context)

#genericモジュールを使用しないバージョン    
def detail(request, poll_id):
    #主キーからオブジェクトを取得。見つからない場合は404を返す
    poll = get_object_or_404(Poll, pk=poll_id)
    return render(request, 'polls/detail.html', {'poll':poll})

#genericモジュールを使用しないバージョン    
def results(request, poll_id):
    poll = get_object_or_404(Poll, pk=poll_id)
    return render(request, 'polls/results.html', {'poll' : poll})

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):
        return render(request, 'polls/detail.html', {
            'poll' : p,
            'error_message' : "You didn't select choice.",
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))

class IndexView(generic.ListView):
    template_name = 'polls/index.html'
    context_object_name = 'latest_poll_list'

    def get_queryset(self):
        return Poll.objects.order_by('-pub_date')[:5]

class DetailView(generic.DetailView):
    template_name = 'polls/detail.html'
    model = Poll

class ResultsView(generic.DetailView):
    template_name = 'polls/results.html'
    model = Poll

#新規Pollフォーム画面
def newpollview(request):
return render(request, 'polls/newpoll.html', {})

#新規Poll作成処理
def newpollpost(request):
p = Poll(
question = request.POST['question'],
pub_date = datetime.now()
)
p.save()
return HttpResponseRedirect(reverse('polls:index'))

#Poll削除処理
def deletepoll(request, poll_id):
print(request.method)
if request.method == 'POST':
p = get_object_or_404(Poll, pk=poll_id)
p.delete()
return HttpResponseRedirect(reverse('polls:index'))

 

polls/templates/polls/detail.html

<h1>{{ poll.question }}</h1>

{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}

<form action="{% url 'polls:vote' poll.id %}" method="post">
{% csrf_token %}
{% 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_text }}</label><br />
{% endfor %}
<input type="submit" value="Vote" />
</form>

 

polls/templates/polls/index.html

{% if latest_poll_list %}
    <script type="text/javascript">
        function confirmDelete(did) {
            if (confirm("削除してもよろしいですか?")){
                document.getElementById(did).submit();
            }
            return false;
        }
    </script>
    <ul>
    {% for poll in latest_poll_list %}
        <li>
            <a href="{% url 'polls:detail' poll.id %}">{{ poll.question }}</a> 
            <form id="form_p{{ poll.id }}" action="{% url 'polls:deletepoll' poll.id %}" method="POST">
                {% csrf_token %}
                <a href="#" onclick="return confirmDelete('form_p{{ poll.id }}');">削除</a>
            </form>
        </li>
    {% endfor %}
    </ul>
{% else %}
    <p>No polls are available.</p>
{% endif %}

<a href="{% url 'polls:newpoll' %}">新しくPollを作成</a>

 

polls/templates/polls/results.html

<h1>{{ poll.question }}</h1>

<ul>
{% for choice in poll.choice_set.all %}
    <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
{% endfor %}
</ul>

<a href="{% url 'polls:detail' poll.id %}">Vote again?</a>

 

 polls/templates/polls/newpoll.html

<h1>New Poll</h1>

{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}

<form action="{% url 'polls:newpollpost'%}" method="post">
{% csrf_token %}
    <input type="text" name="question" id="question" value=""/>
    <input type="submit" value="Submit" />
</form>
このエントリーをはてなブックマークに追加