from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the poll index.")จาก code เป็นการสร้างฟังก์ชั่นเพื่อส่งข้อความออก Browser ปกติ
จากนั้นทำการสร้างไฟล์ urls.py ขึ้นมาในโฟลเดอร์ polls แล้วทำการเขียน code ตามนี้
from django.conf.urls import patterns, url from polls import views urlpatterns = patterns('', url(r'^$', views.index, name='index') )จาก code เป็นการตั้งหน้า default โดยเรียกใช้ฟังก์ชั่น index จากไฟล์ views
ต่อไปเราจะทำการแก้ไขไฟล์ urls.py ของโปรเจ็ค โดยทำการเขียน code ตามนี้
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^polls/', include('polls.urls')), url(r'^admin/', include(admin.site.urls)), )จาก code เมื่อมีการเข้า url http://127.0.0.1:8000/polls/ ก็จะทำการเรียกไฟล์ polls/urls.py และจะได้ output ดังนี้
ต่อไปเราจะทำการเพิ่มฟังก์ชั่น detail, result, vote เข้าไปในไฟล์ polls/views.py ตามนี้
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)
โดยฟังก์ชั่น detail สร้างมาเพื่อโชว์รายละเอียดของ pollresult สร้างมาเพื่อโชว์ผลรับของ poll
vote สร้างมาเพื่อแสดงผลโหวตของ poll
ต่อไปเราจะทำการแก้ไขไฟล์ polls/urls.py โดยเขียน code ตามนี้
from django.conf.urls import patterns, url from polls import views urlpatterns = patterns('', url(r'^$', views.index, name='index'), url(r'^(?P<poll_id>\d+)/$', views.detail, name='detail'), url(r'^(?P<poll_id>\d+)/results/$', views.results, name='results'), url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote'), )จาก code เราเพิ่มขึ้นมา 3 บรรทัด โดย
url(r'^(?P<poll_id>\d+)/$', views.detail, name='detail'),เป็นการรับข้อมูลตัวเลขมาใส่ไว้ใน poll_id และเรียกใช้ฟังก์ชั่น detail จาก views
ตัวอย่างการเรียกใช้ url นี้ เช่น /polls/5
url(r'^(?P<poll_id>\d+)/results/$', views.results, name='results'),เป็นการรับข้อมูลตัวเลขมาใส่ไว้ใน poll_id และเรียกใช้ฟังก์ชั่น results จาก views
ตัวอย่างการเรียกใช้ url นี้ เช่น /polls/5/results
url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote'),เป็นการรับข้อมูลตัวเลขมาใส่ไว้ใน poll_id และเรียกใช้ฟังก์ชั่น vote จาก views
ตัวอย่างการเรียกใช้ url นี้ เช่น /polls/5/vote
ต่อไปเราจะทำการแก้ไขฟังก์ชั่น index และใช้ API ในไฟล์ polls/views.py ตามนี้
from django.http import HttpResponse from polls.models import Poll def index(request): latest_poll_list = Poll.objects.order_by('-pub_date')[:5] output = ', '.join([p.question for p in latest_poll_list]) return HttpResponse(output)จาก code ได้ใช้ API objects.order_by()[] โดยดึง object แล้วทำการ sort โดยวันที่ล่าสุด 5 ลำดับมาเก็บไว้ในตัวแปร latest_poll_list และมาทำการวน for เพื่อดึงข้อมูล question จาก object ที่เก็บไว้ในตัวแปร latest_poll_list และนำมาต่อกันเพื่อเก็บไว้ในตัวแปร output และแสดงออกบน browse
และเมื่อทำการ refresh หน้า default ก็จะแสดงรายชื่อ question 5 ลำดับแรกที่เรียงตามเวลาขึ้นมาดังนี้
จากภาพเนื่องจากมีเพียง 1 question จึงแสดงแค่อย่างเดียว
ต่อไปเราจะทำการสร้าง template โดยเริ่มต้นนั้นให้เราสร้างโฟลเดอร์ templates ไว้ในโฟลเดอร์ polls แล้วเราจะทำการสร้างไฟล์ index.html ไว้ใน polls/templates/polls/ ที่เราสร้างโฟลเดอร์ polls มาอีกชั้นนั้น เพื่อให้เกิดความง่ายในการเรียกใช้ และป้องกันการสับสนหากมีการสร้าง app มากกว่า 1 app ส่วนเวลาเราจะเรียกใช้เราสามารถอ้างถึงได้ง่ายๆเช่น poll/index.html
เริ่มแรกเราจะทำการเพิ่ม code เข้าไปในไฟล์ settings.py ตามนี้
TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]เป็นการกำหนด Directory path ของไฟล์ template เข้าไป
จากนั้นเราจะทำการเขียน code ในไฟล์ index.html ตามนี้
{% if latest_poll_list %} <ul> {% for poll in latest_poll_list %} <li><a href="/polls/{{ poll.id }}/">{{ poll.question }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %}จาก code html จะเป็นการเช็ค latest_poll_list ก่อนจากนั้นจะมาวน latest_poll_list เพื่อจะแสดง link เป็นชื่อ question และเมื่อทำการคลิกจะทำการเรียก url ของฟังก์ชั่น detail เพื่อแสดงรายละเอียด
ต่อไปเราจะทำการแก้ไขฟังก์ชั่น index ในไฟล์ polls/views.py ตามนี้
from django.http import HttpResponse from django.template import RequestContext, loader from polls.models import Poll def index(request): latest_poll_list = Poll.objects.order_by('-pub_date')[:5] template = loader.get_template('polls/index.html') context = RequestContext(request, { 'latest_poll_list': latest_poll_list, }) return HttpResponse(template.render(context))จาก code จะมีการเรียกใช้ template โดยทำการ load template มาจาก poll/index.html และจะทำ context ค่า latest_poll_list ใส่เข้าไปใน template แล้วดึงค่าจาก template ส่งออกไปให้ browser แล้วเราจะได้ผลลัพธ์ดังนี้
ต่อไปจะเป็นการใช้ Shortcut: render()
โดยที่ shortcut: render() นั้น เป็นการย่อ render ให้สั้นลง โดยเราจะแก้ไขฟังก์ชั่น index ใน polls/views.py ตามนี้
from django.shortcuts import render from polls.models import Poll def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] context = {'latest_poll_list': latest_poll_list} return render(request, 'polls/index.html', context)จาก code จะเห็นได้ว่าสั้นลงกว่าเดิมแต่ความหมายและผลลัพธ์เหมือนเดิม
ต่อไปจะเป็นการใช้ 404 error
404 error คือการเรียกหาหน้าเว็บไซต์นั้นๆไม่เจอ หากไม่ใช้เมื่อเกิด error ขึ้น browser จะแสดง code ยืดยาวอาจจะทำให้ผู้ใช้สับสนได้ โดยเราจะแก้ไขฟังก์ชั่น detail ใน polls/views.py ตามนี้
from django.http import Http404 from django.shortcuts import render from polls.models import Poll # ... def detail(request, poll_id): try: poll = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render(request, 'polls/detail.html', {'poll': poll})จาก code จะทำการดึงค่า pk มาเพื่อเทียบกับ poll_id หากไม่เจอจะทำการเรียกใช้ Http404
ต่อไปเราจะสร้างไฟล์ detail.html ไว้ใน polls/templates/polls/ โดยเราจะเขียน code เพียงแค่ {{ poll }} เพื่อที่จะใช้ทดสอบ 404 error การทดสอบ เราจะทำการเข้า http://127.0.0.1:8000/polls/ ปกติ แล้วทำการคลิกจะใช้งานได้ปกติ จากนั้น ให้เราทำการเปลี่ยนตัวเลขของ url ให้เป็น id ที่ไม่มีใน database เช่น http://127.0.0.1:8000/polls/20/ แล้วจะโชว์หน้า 404 error ดังนี้
ต่อไปจะเป็นการใช้ Shortcut: get_object_or_404()
โดยที่ Shortcut: get_object_or_404() นั้น จะเป็นการใช้ 404 error แบบย่อ โดยเราจะทำการแก้ไขฟังก์ชั่น detail ในไฟล์ polls/views.py ตามนี้
from django.shortcuts import render, get_object_or_404 from polls.models import Poll # ... def detail(request, poll_id): poll = get_object_or_404(Poll, pk=poll_id) return render(request, 'polls/detail.html', {'poll': poll})จะเห็นได้ว่า code สั้นลงแต่ยังมีความหมายและผลลัพธ์ เหมือนเดิม
ต่อไปจะเป็นการใช้ template system
โดยเราจะทำการแก้ไขไฟล์ detail.html ใน polls/templates/polls/ โดยเขียน code ตามนี้
<h1>{{ poll.question }}</h1> <ul> {% for choice in poll.choice_set.all %} <li>{{ choice.choice_text }}</li> {% endfor %} </ul>จาก code html ข้างต้น จะเป็นการวน for ใน object choice_set ทั้งหมด เพื่อที่จะนำค่า choice ทั้งหมดมาแสดง จะได้ผลลัพธ์ดังนี้
ต่อไปจะเป็นการ Removing hardcode
โดยเราจะทำการแก้ไขไฟล์ index.html ตามนี้
โดยของเก่าจะเป็น
<li><a href="/polls/{{ poll.id }}/">{{ poll.question }}</a></li>
ให้แก้ไขใหม่เป็น<li><a href="{% url 'detail' poll.id %}">{{ poll.question }}</a></li>จะเห็นได้ว่าจากการอ้างอิง path จะเปลี่ยนเป็นการใช้ url แทน และสามารถกำหนดฟังก์ชั่นของ url ได้ โดยตรง หาก path ของ url ยาวมากกว่านี้ แบบเก่าอาจจะเป็นส่วนที่ยุ่งยากได้
ต่อไปเป็นการใช้งาน Namespacing URL name
ซึ่งเป็นการให้ Django รู้ว่าเรียกใช้ url ใหนหากมีชื่อ url เหมือนกันในคนละ app
โดยเราจะทำการแก้ไขไฟล์ urls.py ของโปรเจ็ค โดยเขียน code ตามนี้
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^polls/', include('polls.urls', namespace="polls")), url(r'^admin/', include(admin.site.urls)), )จาก code จะเห็นได้ว่า เราได้ทำการเพิ่ม namespace="polls" เข้าไปด้านหลังเพื่อระบุว่าตั้งชื่อ namespace ว่า polls
จากนั้นเราจะทำการแก้ไขไฟล์ index.html ที่อยู่ใน polls/templates/polls/
โดยของเก่าจะเป็นดังนี้
<li><a href="{% url 'detail' poll.id %}">{{ poll.question }}</a></li>
ให้แก้ไขใหม่เป็นดังนี้<li><a href="{% url 'polls:detail' poll.id %}">{{ poll.question }}</a></li>จาก code จะเห็นได้ว่าเราได้ใส่ polls: ไปข้างหน้า detail เพื่อบอกให้รู้ว่าจะทำการเรียกใช้ url detail ของ namespace ที่ชื่อว่า polls ซึ่งในที่นี้ก็คือ url ของ app polls
ในบทนี้จะทำให้เราเข้าใจและได้รู้เกี่ยวกับการใช้ URL และ TEMPLATE มากขึ้น
ข้อมูลอ้างอิง : Tutorial part 3






ไม่มีความคิดเห็น:
แสดงความคิดเห็น