[PYTHON] Django note 2

3 MTV In software development, a design pattern called MVC is often used. But Django is an MTV design pattern. M : Model T : Template V : View (Router, for accessing a specific view)

4 Wirte Your First Page : Hello World !

Create View

Create views.py </ font> and this views.py </ font> Write the following source in.

views.py


from django.http import HttpResponse  

def hello(request):
    return HttpResponse("Hello world")

Set URL

Add ʻurl (r'^ hello / $', hello), `in urls.py Like this

urls.py


urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^hello/$', hello),
]

Description

r

It means raw.

'^hello/$'

URLpattern is starting with ^ and ending with $. ^ Is the display that begins the regular expression and $ is the end of the string. Without ^, / foo / hello / will be Matched. Without $, / hello / foo / will be matched.

/ hello / and / hello are different However, if you don't have / hello / and you access / hello, the url will automatically be / hello /.

hello

Next is view name.

RUN visit http://127.0.0.1:8000/hello/

5 Dynamic web page

I created a Hello World page in Django Note 2. This time, we will create a dynamic page.

Create a new model with views.py

views.py


import datetime

def hello(request)
    ...

def current_datetime(request):
    now = datetime.datetime.now()
    html = "It is now %s." % now
    return HttpResponse(html)

Add rules in urls.py

urls.py


urlpatterns = [
      url(r'^admin/', include(admin.site.urls)),
      url(r'^hello/$', hello),
      url(r'^time/$', current_datetime),
]

visit : http://127.0.0.1:8000/time/

Recommended Posts