Sugree

Main menu

  • About
    • Self
  • Project
    • Barcode Generator / Reader
    • GT200
    • GeoPin
    • Mitter
    • Red Mob
    • Thairath Breaking News
    • Twitter Android SDK
    • jibjib
    • microblog-purple
    • English
    • Thai

URL dispatching in Django

Submitted by sugree on Tue, 09/16/2008 - 00:34
  • Django
  • Python
  • Thai

คราวก่อนคงสังเกตุเรื่องขัดตาใน 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

  • http://localhost:8000/
  • http://localhost:8000/helloworld/
  • http://localhost:8000/helloworld/sugree

แค่นี้ helloworld ก็กลายเป็น app อิสระซะที

Roti (alpha) thinks you may like these:
  • Simple template in Django
  • MVC in Django
  • Django - Hello, World!
  • Django 66 - Django Thailand
  • Loop in template
  • Login to post comments

Popular Tags

Android BarCamp BarCampBangkok Book Django Drupal Education Family Google Hardware Hardy Health Interview Intrepid Java jibjib Joke Life microblog-purple OpenOffice.org OpenSource Podcast Python Review SoC Social Network Trip Twitter Ubuntu Weekly Suki
more tags

Powered By

debian
apache
drupal
drupal.in.th
openfreehost
inox
feedburner

© 2007-2008 Sugree Phatanapherom. Creative Commons [Feed Content / Comment]
RoopleTheme