URL dispatching in Django
คราวก่อนคงสังเกตุเรื่องขัดตาใน urls.py ที่น่ารำคาญไปหน่อย ต้องมานั่งเขียน re เพื่อจับคู่กับ view จริงๆ แล้วที่เห็นนั่นเป็นแบบเขียนเล่น เขียนง่ายๆ เวลาใช้จริงเราจะโยนหน้าที่พวกนี้กระจายให้แต่ละ app ในที่นี้ก็คือ helloworld ซึ่งควรจะจัดการกับ url ของตัวเองทั้งหมดด้วยตนเอง นั่นแปลว่า ทำ app เสร็จก็ยกไปใช้ที่โปรเจคอื่นได้ทันที ไม่ต้องมานั่งทำ urls.py เอง แต่ถ้าอยากเปลี่ยน url ก็ทำได้เช่นกัน
วิธีทำก็แสนง่าย ย้าย urls.py ไปเป็น helloworld/urls.py โดยไม่มีอะไรเปลี่ยนแปลง
from django.conf.urls.defaults import * urlpatterns = patterns('', (r'^$', 'samplesite.helloworld.views.index'), (r'^(?P<name>.*)$', 'samplesite.helloworld.views.entity'), )
แล้วแก้ urls.py
from django.conf.urls.defaults import * urlpatterns = patterns('', (r'^helloworld/', include('samplesite.helloworld.urls')), )
แล้วลองรันดู
./manage.py runserverทดสอบเปิด url
แค่นี้ helloworld ก็กลายเป็น app อิสระซะที
Roti (alpha) thinks you may like these:
- Login to post comments






