【Python】djangoのチュートリアルをやってみる<その3>

2019年2月3日

前回の続きでさらにdjangoチュートリアルを進めていきます。

【Python】djangoのチュートリアルをやってみる<その2>

 

フォームを作成する

polls/detail.html」でフォームを使用するようにします。以下のように修正します。

[highlight_python]

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

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

<form action=”{% url ‘polls:vote’ question.id %}” method=”post”>
{% csrf_token %}
{% for choice in question.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>

[/highlight_python]

投票(vote)機能を追加します。「polls/views.py」のvote()関数をちゃんとしたものにします。

[highlight_python]

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse

from .models import Choice, Question

# 途中のコードは省略

def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST[“choice”])
except (KeyError, Choice.DoesNotExist):
# エラー時はエラーメッセージを表示する
return render(request,”polls/detail.html”,{“question”: question, “error_message”: “You didn’t select a choice.”},)
else:
selected_choice.votes += 1
selected_choice.save()
# 成功した際は結果画面へリダイレクトする
return HttpResponseRedirect(reverse(“polls:results”, args=(question.id,)))

[/highlight_python]

reverse()関数では第一引数でビューを指定し、第二引数でビューに渡すパラメータを定義します。

それによって、reusltsビューを表示します。

resultsもしっかり書き換えます。

[highlight_python]

def results(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, ‘polls/results.html’, {‘question’: question})

[/highlight_python]

ここで「results.html」を定義したので、新規作成します。

[highlight_python]

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

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

<a href=”{% url ‘polls:detail’ question.id %}”>Vote again?</a>

[/highlight_python]

 

汎用ビューを使う

これまで作成した各ビューを汎用ビューとして使うようにします。汎用ビューにすることでコーディング量を減らすことができます。

polls/url.py」を以下のように修正します。

[highlight_python]

from django.urls import path

from . import views

app_name = ‘polls’
urlpatterns = [
path(”, views.IndexView.as_view(), name=’index’),
path(‘<int:pk>/’, views.DetailView.as_view(), name=’detail’),
path(‘<int:pk>/results/’, views.ResultsView.as_view(), name=’results’),
path(‘<int:question_id>/vote/’, views.vote, name=’vote’),
]

[/highlight_python]

次に各ビューの記載を修正します。

polls/views.py」を以下のように書き換え、汎用ビューとして読み込むように修正します。

[highlight_python]

from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.views import generic

from .models import Choice, Question

class IndexView(generic.ListView):
template_name = ‘polls/index.html’
context_object_name = ‘latest_question_list’

def get_queryset(self):
“””Return the last five published questions.”””
return Question.objects.order_by(‘-pub_date’)[:5]

class DetailView(generic.DetailView):
model = Question
template_name = ‘polls/detail.html’

class ResultsView(generic.DetailView):
model = Question
template_name = ‘polls/results.html’

def vote(request, question_id):
… # 以下はそのまま

[/highlight_python]

 

テストに関して

チュートリアルにはテストに関するものもありますが、ここは一旦飛ばします。

個人開発でしっかりテストを作成するかも分かりませんし、私個人としてテストの作りはチュートリアルよりもベストプラクティスを参照するのが良いと考えているためです。

テストは必要になったらまた一から勉強します。

 

静的コンテンツを管理する

アプリケーション内で使用する静的なコンテンツを管理するディレクトリを作成します。

チュートリアルではアプリケーション下にstaticフォルダを作成するようにしていますが、テンプレートと同様でプルジェクト直下で管理します。

「mysite/static/polls」でディレクトリを作成します。

その下に「style.css」を以下のような内容で作成します。

[highlight_python]

li a {
color: green;
}

[/highlight_python]

polls/index.html」に以下を追加します。

[highlight_markup]

{% load static %}

<link rel=”stylesheet” type=”text/css” href=”{% static ‘polls/style.css’ %}”>

[/highlight_markup]

 

polls/settings.py」にstaticディレクトリのパスを設定するため、以下のこーどを追加します。

[highlight_python]

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/

STATIC_URL = “/static/”

# 以下の行を追加

STATICFILES_DIRS = (os.path.join(BASE_DIR, “static”),)

[/highlight_python]

こちらでstaticディレクトリの設定ができました。URLにアクセスすると、文字が緑に変わっていると思います。

http://localhost:8000/polls/

 

ここまでで、投票アプリ本体のチュートリアルはいったん終了です。

残りは管理機能のチュートリアルとなります。