Tutorial 3 started. From this time, you will learn how to create a public page.
The following description is required, but it is created automatically at the start project. setting.py ######
ROOT_URLCONF = 'mysite.urls'
The same applies to URLConf in urls.py. First, add a pattern here.
urls.py ######
from django.conf.urls import patterns, include, url #add to
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# url(r ‘URL pattern’,‘Corresponding view function’)How to write
url(r'^polls/$', 'polls.views.index'), #add to
url(r'^polls/(?P<poll_id>\d+)/$', 'polls.views.detail'), #add to
url(r'^polls/(?P<poll_id>\d+)/results/$', 'polls.views.results'), #add to
url(r'^polls/(?P<poll_id>\d+)/vote/$', 'polls.views.vote'), #add to
url(r'^admin/', include(admin.site.urls))
)
Basic: http://www.mnet.ne.jp/~nakama/ Python:http://docs.python.jp/2.7/library/re.html#module-re
It seems that ^ means the start point and $ means the end point, so
As for ‘(? P <poll_id> \ d +)’, if you try to disassemble it from what you know,
This is used when evaluating multiple characters at once.
It seems that the following corresponding character strings are assigned to poll_id.
It seems that this can also be written as'[0-9]'.
In other words, when it comes to ‘\ d +’ collectively, one or more half-width numbers are applicable.
For the time being, all patterns are changed from ‘^’ to ‘$’, so the expression specified inside it will be excluded.
views.py ######
from django.http import HttpResponse
def index(request): # index.html-like role
return HttpResponse("Hello, world. You're at the poll index.")
def detail(request, poll_id): # url:/polls/1/Display with
return HttpResponse("You're looking at poll %s." % poll_id)
def results(request, poll_id): # url:/polls/1/results/Display with
return HttpResponse("You're looking at the results of poll %s." % poll_id)
def vote(request, poll_id): # url:/polls/1/vote/Display with
return HttpResponse("You're voting on poll %s." % poll_id)
Functions after detail have poll_id as the first argument. In the previous url (r'URL pattern','view function'), if the URL matches the regular expression, it seems that the value assigned to'? P \ <poll_id>' is passed to the second argument of the view function. (Since they were'\ d +', they are half-width numbers with one or more digits. If it is'url: / pols / 1 /', it is '1'). ** I changed the name and it didn't work, so I may have acquired it as a variable. ** **
When I accessed each URL, it was displayed properly.
Recommended Posts