Sunday, September 26, 2010

Learning Django: Create Views

Creaet Views

Django ใช้การพัฒนาในแบบ MTV คือ Model, Template, และ View ในส่วนนี้เราจะมาดูเรื่อง View กัน

เริ่มต้นจากการสร้างไฟล์ที่ชื่อ

views.py


from django.http import HttpResponse
def hello(request):
return HttpResponse("Hello world")


เป็นไฟล์ python ทีมี module เดียวชื่อ hello ซึ่งจะถือเป็น view อันหนึ่ง ลองรัน web server (python manage.py runserver) ดูก็จะไม่เห็นการเปลี่ยนแปลงใดๆ เนื่องจากยังไม่ได้มีการ map view ที่ชื่อ hello นี้เข้ากับ pattern ใดๆ ซึ่งคงเดาใด้ว่า การ map นี้เรากำหนดไว้ในไฟล์ urls.py

ลองดูเนื้อหาในไฟล์ urls.py ที่ Django สร้างขึ้นมาให้ (ตัวอย่างนี้ลบ comment ออกแล้ว)


from django.conf.urls.defaults import *


urlpatterns = patterns('',
)

ในส่วนนี้จะเป็นการกำหนดการ map ระหว่าง pattern กับ view จะเห็นว่าเรายังไม่มีการ map ใดๆ (พารามิเตอร์ตัวแรกไม่ได้อ้างถึงการ map) ดังนั้น ไม่ว่าเราจะ browse ไปที่ใดใน http://127.0.0.1:8000/ ก็ยังจะขึ้นหน้าเหมือนเดิม (ไม่มี error 404)

ทีนี้เราจะ map view hello เข้ากับ url http://127.0.0.1:8000/hello/ โดยการแก้ไข urls.py ตามขั้นตอนดังนี้
1. import module hello โดยใช้คำสั่ง from mysite.views import hello
2. เพิ่ม map ระหว่าง view hello กับ pattern /hello/ โดยเพิ่ม  ('^hello/$', hello) เข้าไปใน urlpatterns
(พารามิเตอร์แรกเป็น pattern เป็น regular exprssion โดย '^' หมายถึงจุดเริ่่ม pattern '$' หมายถึงจุดสิ้นสุด ถ้าเรากำหนดเป็น 'hello' ธรรมดา มันจะไปตรงกับ path อื่นเช่น http://127.0.0.1:8000/hello/test/ เป็นต้น ส่วนพารามิเตอร์ที่สองเป็นชื่อ view ที่กำหนดไว้ใน module)

ไฟล์ที่แก้ไขแล้วจะมีลักษณะดังนี้


from django.conf.urls.defaults import *
from mysite.views import hello


urlpatterns = patterns('',
    ('^hello/$', hello),
)
*หลัง  ('^hello/$', hello) ต้องมี  "," ด้วย

เมื่อลองทดสอบ run server ดู จะสามารถ browse view ที่ชื่อ hello โดยผ่าน url http://127.0.0.1:8000/hello/
แล้วถ้าไปยัง path อื่นคราวนี้จะเกิด error 404 ขึ้น

เราสามารถสร้าง view แบบไดนามิกได้ ลองดูตัวอย่าง code ที่เพิ่มขึ้นใน views.py

from django.http import HttpResponse
import datetime

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

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

แลัวแก้ไข urlpatterns เป็น

urlpatterns = patterns('',
    ('^hello/$', hello),
    ('^time/$', current_datetime),
)


เป็นการเพิ่ม view ขื่อ current_datetime ขึ้นมาอีก โดย view นี้ไม่ใช่ view แบบ static มีการเปลี่ยนแปลงเนื้อหาทุกครั้ง


Dynamic URL

ทีนี้เราจะมาลอง map dynamic URL เริ่มต้นที่ การแก้ไข urlpatterns

urlpatterns = patterns('',
    (r'^hello/$', hello),
    (r'^time/$', current_datetime),
    (r'^time/plus/(\d{1,2})/$', hours_ahead),
)

เราได้สร้าง map สำหรับ pattern time/plus/(\d{1,2}) (ถ้าไม่เข้าใจลองหาอ่านเรื่อง regular expression) ซึ่งทำให้สามารถส่งผ่านค่าในวงเล็บไปให้กับ view ได้เสมือนเป็น parameter ใน view 

สังเกตว่าเราใช้ r นำหน้า pattern เพื่อไม่ให้ python ทำการประมวลผล escape sequence

โคดสำหรั้บ hours_ahead view

from django.http import Http404, HttpResponse
import datetime

def hours_ahead(request, offset):
    try:
        offset = int(offset)
    except ValueError:
        raise Http404()
    dt = datetime.datetime.now() + datetime.timedelta(hours=offset)
    html = "In %s hour(s), it will be %s." % (offset, dt)
    return HttpResponse(html)











No comments:

Post a Comment