フロントを作る
手順は
- urls.pyの編集
- views.pyの編集
- templateの作成
urls.py 内の urlpatterns に以下を追加。正規表現を使ってURLを解釈し、指定したメソッドを起動する。
url(r'^polls/$', 'polls.views.index'),
url(r'^polls/(?P<poll_id>\d+)/$', 'polls.views.detail'),
url(r'^polls/(?P<poll_id>\d+)/results/$', 'polls.views.results'),
url(r'^polls/(?P<poll_id>\d+)/vote/$', 'polls.views.vote'),
?P<poll_id> は一致した文字列を、poll_idにセットして、メソッドのパラメータに渡してくれる。\d+ は1文字以上の数字にマッチするという意味
次は view.py に対応するメソッドを定義する。
from django.template import Context, loader
from django.http import HttpResponse
from polls.models import Poll
def index(request):
return HttpResponse('Hello, this is polls index page.')
def detail(request, poll_id):
return HttpResponse("You're looking at poll %s." % poll_id)
def results(request, poll_id):
return HttpResponse("You're looking at the results of poll %s." % poll_id)
def vote(request, poll_id):
return HttpResponse("You're voting on poll %s." % poll_id)
とりあえず文字だけ返すようなのを作った。
この時点でメソッドが呼ばれるかどうかチェック。
サーバーを起動し
http://localhost:8000/polls/
http://localhost:8000/polls/1
http://localhost:8000/polls/1/results
http://localhost:8000/polls/1/vote
で確認。
次にテンプレートを使った表示
適当なテンプレート用ディレクトリを作成する。
settings.py を開いて、TEMPLATE_DIRS にフルパスで追加する。
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
'/home/user/django-projects/mysite/templates'
)
テンプレート用ディレクトリに polls ディレクトリを作成し、その中に index.html を作成する。
index.html
{% if latest_polls %}
<ul>
{% for poll in latest_polls %}
<li><a href="/polls/{{poll.id}}/">{{poll.question}}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
感覚的に何をやってるかは分かると思う。
テンプレートの利用を views.py で記述する
from django.template import Context, loader
def index(request):
latest_polls = Poll.objects.all().order_by('-pub_date')[:5]
template = loader.get_template('polls/index.html')
context = Context({'latest_polls': latest_polls, })
return HttpResponse(template.render(context))
上のは少し冗長で、こっちの書き方のが簡単。
from django.shortcuts import render_to_response
def index(request):
latest_polls = Poll.objects.all().order_by('-pub_date')[:5]
return render_to_response('polls/index.html', {'latest_polls': latest_polls})
最終更新:2012年10月27日 11:41