18
23

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

DJangoメモ:はじめから(ビューを作る編)

Last updated at Posted at 2013-12-13

チュートリアル3を開始。
今回からは公開用のページを作るやり方を学びます。

URLConf設定を書く

以下の記述が必要だがstartproject時に自動的に作られている。

setting.py
ROOT_URLCONF = 'mysite.urls'

urls.py内のURLConfも同様。まずはここにパターンを追加していく。

urls.py
from django.conf.urls import patterns, include, url  # 追加

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # url(r’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'),  # 追加
    url(r'^admin/', include(admin.site.urls))
) 
正規表現が全く分からないためググりました。

基本:http://www.mnet.ne.jp/~nakama/
Python:http://docs.python.jp/2.7/library/re.html#module-re

^は開始地点、$は終了地点を意味するらしいので、

  • ’^polls$’は「’polls’以外は許さない」という意味(たぶん)

‘(?P\d+)’に関しては分かるところから解体してみると、

  • ()はグループ化

複数文字をまとめて評価する場合にこれでくくる。

  • ‘?P’は変数宣言みたいなもの?

以降の該当文字列をpoll_idに代入している感じと思われる。

  • ’\d’は半角の0から9

これは’[0-9]’とも書けるっぽい。

  • ’+’は1回以上の繰り返しているかどうか

つまりまとめて’\d+’となると一桁以上の半角数字が該当。

とりあえずどのパターンも’^’から’$’になっているのでその内側で指定した表現は排除されるということだろう。

ビューを作る

views.py
from django.http import HttpResponse

def index(request):  # index.html的な役回り
    return HttpResponse("Hello, world. You're at the poll index.")

def detail(request, poll_id):  # url:/polls/1/で表示
    return HttpResponse("You're looking at poll %s." % poll_id)
def results(request, poll_id):  # url:/polls/1/results/で表示
    return HttpResponse("You're looking at the results of poll %s." % poll_id)
def vote(request, poll_id):  # url:/polls/1/vote/で表示
    return HttpResponse("You're voting on poll %s." % poll_id)

detail以降の関数は第に引数にpoll_idが入る。
先ほどのurl(r’URLパターン’,’ビュー関数’)では、URLが正規表現にマッチしていたらビュー関数の第2引数に’?P<poll_id>’に代入された値が渡されるらしい(それはいずれも’\d+’だったので一桁以上の半角数字になる。’url:/pols/1/’だったら’1’)。
名前を変えると駄目になったので、変数として取得しているのかもしれない。

それぞれのURLにアクセスすると、たしかにちゃんと表示された。

18
23
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
23

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?