5. Hello World url dispatcher
"A clean, elegant URL scheme is an important detail in a high-quality Web application. Django lets you design URLs however you want, with no framework limitations."
- https://docs.djangoproject.com/en/dev/topics/http/urls/
In this section, we'll take the url thing.
In our previous HelloWorld project, we used the urls.py like this:
from django.conf.urls import patterns, include, url from HelloWorldApp.views import foo urlpatterns = patterns('', url(r'HelloWorldApp/$', foo), )
However, there are couple of other ways of composing url to get the same mapping to the view.
Before looking for other ways, let's check how the url requests are processed by Django.
When a user requests a page from our Django-powered site, this is the algorithm the system follows to determine which Python code to execute:
- Django loads that Python module and looks for the variable urlpatterns. This should be a python list, in the format returned by the function django.conf.urls.patterns().
- Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL.
- Once one of the regexes matches, Django imports and calls the given view, which is a simple python function (or a class based view). The view gets passed an HttpRequest as its first argument and any values captured in the regex as remaining arguments.
- If no regex matches, or if an exception is raised during any point in this process, Django invokes an appropriate error-handling view.
When the url box has nothing but http://localhost:8000/, we can use this:
from django.conf.urls import patterns, include, url urlpatterns = patterns('', url(r'^$', 'HelloWorldApp.views.foo', name='home') )
Since Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL, we may want to put several options in the file, like this:
from django.conf.urls import patterns, include, url from HelloWorldApp.views import foo urlpatterns = patterns('', url(r'HelloWorldApp/$', foo), url(r'^$', foo, name='home') )
The first regex is for the case when we type in "/HelloWorldApp" in the url:
and the second one is for the default (nothing):
How we can passing data to view from url dispatcher?
# urls.py urlpatterns += patterns('', url(r'^places/(?P<name>\w+)/$', 'misc.views.home', name='places.view_place') ) # views.py def home(request, name): place = models.Place.objects.get(name__iexact=name)
For more on url dispatcher, check Django doc: URL dispatcher.
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization