Monday, July 6, 2009

Django MVC Basics Pt 1: URLconf

The URLconf - mapping between URLs and view functions that should be called for those URLs.

from django.conf.urls.defaults import *

# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

urlpatterns = patterns('',
# Example:
# (r'^mysite/', include('mysite.foo.urls')),

# Uncomment the admin/doc line below and add 'django.contrib.admindocs'
# to INSTALLED_APPS to enable admin documentation:
# (r'^admin/doc/', include('django.contrib.admindocs.urls')),

# Uncomment the next line to enable the admin:
# (r'^admin/', include(admin.site.urls)),
)
Important to note are:
r - Python indication that the string is a "raw string", i.e. do not interpret characters.
' ' - string enclosed in single quotes
^ - caret, a regular expression meaning "require that the pattern matches the start of the string"
$ - dollar sign, regex meaning "require the pattern match the end of the string".

e.g. ensures this works: www.url.com/hello/
and this does not: www.url.com/hello/there (thanks to $)
and this does not:www.url.com/there/hello (thanks to ^)

See table of basic Regular Expressions - from the Django Book.

The second parameter in the 2-tuple sometimes begins with include(... and sometimes does not. It is the function to be associated with the specified URL. The function's first parameter is always the HttpRequest object. Always. Here's documentation on the HttpRequest object's API.

No comments: