Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Beefed up docs/url_dispatch.txt

git-svn-id: http://code.djangoproject.com/svn/django/trunk@1291 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit f125fb0afc2e00612701f825c8456acdcb53e55b 1 parent cdbc94d
Adrian Holovaty authored November 19, 2005
12  docs/overview.txt
@@ -162,9 +162,9 @@ Reporter/Article example, here's what that might look like::
162 162
     from django.conf.urls.defaults import *
163 163
 
164 164
     urlpatterns = patterns('',
165  
-        (r'^/articles/(?P<year>\d{4})/$', 'myproject.news.views.articles.year_archive'),
166  
-        (r'^/articles/(?P<year>\d{4})/(?P<month>\d{2})/$', 'myproject.news.views.articles.month_archive'),
167  
-        (r'^/articles/(?P<year>\d{4})/(?P<month>\d{2})/(?P<article_id>\d+)/$', 'myproject.news.views.articles.article_detail'),
  165
+        (r'^/articles/(?P<year>\d{4})/$', 'myproject.news.views.year_archive'),
  166
+        (r'^/articles/(?P<year>\d{4})/(?P<month>\d{2})/$', 'myproject.news.views.month_archive'),
  167
+        (r'^/articles/(?P<year>\d{4})/(?P<month>\d{2})/(?P<article_id>\d+)/$', 'myproject.news.views.article_detail'),
168 168
     )
169 169
 
170 170
 The code above maps URLs, as regular expressions, to the location of Python
@@ -181,7 +181,7 @@ dictionaries -- and the values captured in the regex, via keyword
181 181
 arguments.
182 182
 
183 183
 For example, if a user requested the URL "/articles/2005/05/39323/", Django
184  
-would call the function ``myproject.news.views.articles.article_detail(request,
  184
+would call the function ``myproject.news.views.article_detail(request,
185 185
 year='2005', month='05', article_id='39323')``.
186 186
 
187 187
 Write your views
@@ -280,8 +280,8 @@ This has been only a quick overview of Django's functionality. Some more useful
280 280
 features:
281 281
 
282 282
     * A caching framework that integrates with memcached or other backends.
283  
-    * An RSS framework that makes creating RSS feeds as easy as writing a
284  
-      small Python class.
  283
+    * A syndication framework that makes creating RSS and Atom feeds as easy as
  284
+      writing a small Python class.
285 285
     * More sexy automatically-generated admin features -- this overview barely
286 286
       scratched the surface.
287 287
 
14  docs/tutorial03.txt
@@ -60,6 +60,7 @@ regular expression as keyword arguments, and, optionally, arbitrary keyword
60 60
 arguments from the dictionary (an optional third item in the tuple).
61 61
 
62 62
 For more on ``HTTPRequest`` objects, see the `request and response documentation`_.
  63
+For more details on URLconfs, see the `URLconf documentation`_.
63 64
 
64 65
 When you ran ``django-admin.py startproject myproject`` at the beginning of
65 66
 Tutorial 1, it created a default URLconf in ``myproject/urls.py``. It also
@@ -67,8 +68,7 @@ automatically set your ``ROOT_URLCONF`` setting to point at that file::
67 68
 
68 69
     ROOT_URLCONF = 'myproject.urls'
69 70
 
70  
-Time for an example. Edit ``myproject/urls.py`` so it looks like
71  
-this::
  71
+Time for an example. Edit ``myproject/urls.py`` so it looks like this::
72 72
 
73 73
     from django.conf.urls.defaults import *
74 74
 
@@ -88,9 +88,9 @@ associated Python package/module: ``myproject.apps.polls.views.detail``. That
88 88
 corresponds to the function ``detail()`` in ``myproject/apps/polls/views.py``.
89 89
 Finally, it calls that ``detail()`` function like so::
90 90
 
91  
-    detail(request=<HttpRequest object>, poll_id=23)
  91
+    detail(request=<HttpRequest object>, poll_id='23')
92 92
 
93  
-The ``poll_id=23`` part comes from ``(?P<poll_id>\d+)``. Using
  93
+The ``poll_id='23'`` part comes from ``(?P<poll_id>\d+)``. Using
94 94
 ``(?P<name>pattern)`` "captures" the text matched by ``pattern`` and sends it
95 95
 as a keyword argument to the view function.
96 96
 
@@ -103,6 +103,11 @@ something like this::
103 103
 
104 104
 But, don't do that. It's silly.
105 105
 
  106
+Note that these regular expressions do not search GET and POST parameters, or
  107
+the domain name. For example, in a request to ``http://www.example.com/myapp/``,
  108
+the URLconf will look for ``/myapp/``. In a request to
  109
+``http://www.example.com/myapp/?page=3``, the URLconf will look for ``/myapp/``.
  110
+
106 111
 If you need help with regular expressions, see `Wikipedia's entry`_ and the
107 112
 `Python documentation`_. Also, the O'Reilly book "Mastering Regular
108 113
 Expressions" by Jeffrey Friedl is fantastic.
@@ -113,6 +118,7 @@ time the URLconf module is loaded. They're super fast.
113 118
 .. _Wikipedia's entry: http://en.wikipedia.org/wiki/Regular_expression
114 119
 .. _Python documentation: http://www.python.org/doc/current/lib/module-re.html
115 120
 .. _request and response documentation: http://www.djangoproject.com/documentation/request_response/
  121
+.. _URLconf documentation: http://www.djangoproject.com/documentation/url_dispatch/
116 122
 
117 123
 Write your first view
118 124
 =====================
267  docs/url_dispatch.txt
@@ -2,52 +2,244 @@
2 2
 URL dispatcher
3 3
 ==============
4 4
 
5  
-We're fanatics about good URLs. No ".php" or ".cgi", and certainly not any of
6  
-that "0,2097,1-1-1928,00" nonsense. Django's URL dispatcher lets you design
7  
-your URLs to be as pretty as the rest of your application.
  5
+A clean, elegant URL scheme is an important detail in a high-quality Web
  6
+application. Django lets you design URLs however you want, with no framework
  7
+limitations.
8 8
 
9  
-See `the Django overview`_ for a quick introduction to URL configurations; this
10  
-document will continue from there.
  9
+There's no ``.php`` or ``.cgi`` required, and certainly none of that
  10
+``0,2097,1-1-1928,00`` nonsense.
11 11
 
12  
-.. _`the Django overview`: http://www.djangoproject.com/documentation/overview/#design-your-urls
  12
+See `Cool URIs don't change`_, by World Wide Web creator Tim Berners-Lee, for
  13
+excellent arguments on why URLs should be clean and usable.
  14
+
  15
+.. _http://www.w3.org/Provider/Style/URI: Cool URIs don't change
  16
+
  17
+Overview
  18
+========
  19
+
  20
+To design URLs for an app, you create a Python module informally called a
  21
+**URLconf** (URL configuration). This module is pure Python code and
  22
+is a simple mapping between URL patterns (as simple regular expressions) to
  23
+Python callback functions (your views).
  24
+
  25
+This mapping can be as short or as long as needed. It can reference other
  26
+mappings. And, because it's pure Python code, it can be constructed
  27
+dynamically.
  28
+
  29
+How Django processes a request
  30
+==============================
  31
+
  32
+When a user requests a page from your Django-powered site, this is the
  33
+algorithm the system follows to determine which Python code to execute:
  34
+
  35
+    1. The system looks at the ``ROOT_URLCONF`` setting in your
  36
+       `settings file`_. This should be a string representing the full Python
  37
+       import path to your URLconf. For example: ``"mydjangoapps.urls"``.
  38
+    2. The system loads that Python module and looks for the variable
  39
+       ``urlpatterns``. This should be a Python list, in the format returned
  40
+       by the function ``django.conf.urls.defaults.patterns()``.
  41
+    3. The system runs through each URL pattern, in order, and stops at the
  42
+       first one that matches the requested URL.
  43
+    4. Once one of the regexes matches, Django imports and calls the given
  44
+       view, which is a simple Python function. The view gets passed a
  45
+       `request object`_ and any values captured in the regex as keyword
  46
+       arguments.
  47
+
  48
+.. _settings file: http://www.djangoproject.com/documentation/settings/
  49
+.. _request object: http://www.djangoproject.com/documentation/request_response/#httprequest-objects
  50
+
  51
+Example
  52
+=======
  53
+
  54
+Here's a sample URLconf::
  55
+
  56
+    from django.conf.urls.defaults import *
  57
+
  58
+    urlpatterns = patterns('',
  59
+        (r'^/articles/2003/$', 'news.views.special_case_2003'),
  60
+        (r'^/articles/(?P<year>\d{4})/$', 'news.views.year_archive'),
  61
+        (r'^/articles/(?P<year>\d{4})/(?P<month>\d{2})/$', 'news.views.month_archive'),
  62
+        (r'^/articles/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d+)/$', 'news.views.article_detail'),
  63
+    )
  64
+
  65
+Notes:
  66
+
  67
+    * ``from django.conf.urls.defaults import *`` makes the ``patterns``
  68
+      function available.
  69
+
  70
+    * To capture a value from the URL, use the syntax ``(?P<name>pattern)``,
  71
+      where ``name`` is the name for that value and ``pattern`` is some pattern
  72
+      to match.
  73
+
  74
+    * The ``"r"`` in front of each regular expression string is optional but
  75
+      recommended. It tells Python that a string is "raw" -- that nothing in
  76
+      the string should be escaped. See `Dive Into Python's explanation`_.
  77
+
  78
+Examples:
  79
+
  80
+    * A request to ``/articles/2005/03/`` would match the third entry in the
  81
+      list. Django would call the function
  82
+      ``news.views.month_archive(request, year='2005', month='03')``.
  83
+
  84
+    * ``/articles/2005/3/`` would not match any URL patterns, because the
  85
+      third entry in the list requires two digits for the month.
  86
+
  87
+    * ``/articles/2003/`` would match the first pattern in the list, not the
  88
+      second one, because the patterns are tested in order, and the first one
  89
+      is the first test to pass. Feel free to exploit the ordering to insert
  90
+      special cases like this.
  91
+
  92
+    * ``/articles/2003`` would not match any of these patterns, because each
  93
+      pattern requires that the URL end with a slash.
  94
+
  95
+    * ``/articles/2003/03/3/`` would match the final pattern. Django would call
  96
+      the function
  97
+      ``news.views.article_detail(request, year='2003', month='03', day='3')``.
  98
+
  99
+.. _Dive Into Python's explanation: http://diveintopython.org/regular_expressions/street_addresses.html#re.matching.2.3
  100
+
  101
+What the URLconf searches against
  102
+=================================
  103
+
  104
+The URLconf searches against the requested URL, as a normal Python string. This
  105
+does not include GET or POST parameters, or the domain name.
  106
+
  107
+For example, in a request to ``http://www.example.com/myapp/``, the URLconf
  108
+will look for ``/myapp/``.
  109
+
  110
+In a request to ``http://www.example.com/myapp/?page=3``, the URLconf will look
  111
+for ``/myapp/``.
  112
+
  113
+Syntax of the urlpatterns variable
  114
+==================================
  115
+
  116
+``urlpatterns`` should be a Python list, in the format returned by the function
  117
+``django.conf.urls.defaults.patterns()``. Always use ``patterns()`` to create
  118
+the ``urlpatterns`` variable.
  119
+
  120
+Convention is to use ``from django.conf.urls.defaults import *`` at the top of
  121
+your URLconf. This gives your module access to these objects:
  122
+
  123
+patterns
  124
+--------
  125
+
  126
+A function that takes a prefix an arbitrary number of URL patterns and returns
  127
+a list of URL patterns in the format Django needs.
  128
+
  129
+The first argument to ``patterns()`` is a string ``prefix``. See
  130
+"The view prefix" below.
  131
+
  132
+The remaining arguments should be tuples in this format::
  133
+
  134
+    (regular expression, Python callback function [, optional dictionary])
  135
+
  136
+...where ``dictionary_of_extra_arguments`` is optional. (See
  137
+"Passing extra options to view functions" below.)
  138
+
  139
+handler404
  140
+----------
  141
+
  142
+A string representing the full Python import path to the view that should be
  143
+called if none of the URL patterns match.
  144
+
  145
+By default, this is ``'django.views.defaults.page_not_found'``. That default
  146
+value should suffice.
  147
+
  148
+handler500
  149
+----------
  150
+
  151
+A string representing the full Python import path to the view that should be
  152
+called in case of server errors. Server errors happen when you have runtime
  153
+errors in view code.
  154
+
  155
+By default, this is ``'django.views.defaults.server_error'``. That default
  156
+value should suffice.
  157
+
  158
+include
  159
+-------
  160
+
  161
+A function that takes a full Python import path to another URLconf that should
  162
+be "included" in this place. See "Including other URLconfs" below.
  163
+
  164
+Notes on capturing text in URLs
  165
+===============================
  166
+
  167
+Each captured argument is sent to the view as a plain Python string, regardless
  168
+of what sort of match the regular expression makes. For example, in this
  169
+URLconf::
  170
+
  171
+    (r'^/articles/(?P<year>\d{4})/$', 'news.views.year_archive'),
  172
+
  173
+...the ``year`` argument to ``news.views.year_archive()`` will be a string, not
  174
+an integer, even though the ``\d{4}`` will only match integer strings.
  175
+
  176
+A convenient trick is to specify default parameters for your views' arguments.
  177
+Here's an example URLconf and view::
  178
+
  179
+    # URLconf
  180
+    urlpatterns = patterns('',
  181
+        (r'^/blog/$', 'blog.views.page'),
  182
+        (r'^/blog/page(?P<num>\d+)/$', 'blog.views.page'),
  183
+    )
  184
+
  185
+    # View (in blog/views.py)
  186
+    def page(request, num="1"):
  187
+        # Output the appropriate page of blog entries, according to num.
  188
+
  189
+In the above example, both URL patterns point to the same view --
  190
+``blog.views.page`` -- but the first pattern doesn't capture anything from the
  191
+URL. If the first pattern matches, the ``page()`` function will use its
  192
+default argument for ``num``, ``"1"``. If the second pattern matches,
  193
+``page()`` will use whatever ``num`` value was captured by the regex.
  194
+
  195
+Performance
  196
+===========
  197
+
  198
+Each regular expression in a ``urlpatterns`` is compiled the first time it's
  199
+accessed. This makes the system blazingly fast.
13 200
 
14 201
 The view prefix
15 202
 ===============
16 203
 
17  
-Here's the example from that overview::
  204
+You can specify a common prefix in your ``patterns()`` call, to cut down on
  205
+code duplication.
  206
+
  207
+Here's the example URLconf from the `Django overview`_::
18 208
 
19 209
     from django.conf.urls.defaults import *
20 210
 
21 211
     urlpatterns = patterns('',
22  
-        (r'^/articles/(?P<year>\d{4})/$', 'myproject.news.views.articles.year_archive'),
23  
-        (r'^/articles/(?P<year>\d{4})/(?P<month>\d{2})/$', 'myproject.news.views.articles.month_archive'),
24  
-        (r'^/articles/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d+)/$', 'myproject.news.views.articles.article_detail'),
  212
+        (r'^/articles/(?P<year>\d{4})/$', 'myproject.news.views.year_archive'),
  213
+        (r'^/articles/(?P<year>\d{4})/(?P<month>\d{2})/$', 'myproject.news.views.month_archive'),
  214
+        (r'^/articles/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d+)/$', 'myproject.news.views.article_detail'),
25 215
     )
26 216
 
27  
-The first argument to ``patterns`` is an empty string in the above example, but
28  
-that argument can be useful. The first argument is prepended to all the view
29  
-functions in the urlpatterns list, so the above example could be written more
30  
-concisely as::
  217
+In this example, each view has a common prefix -- ``"myproject.news.views"``.
  218
+Instead of typing that out for each entry in ``urlpatterns``, you can use the
  219
+first argument to the ``patterns()`` function to specify a prefix to apply to
  220
+each view function.
  221
+
  222
+With this in mind, the above example can be written more concisely as::
  223
+
  224
+    from django.conf.urls.defaults import *
31 225
 
32  
-    urlpatterns = patterns('myproject.news.views.articles',
  226
+    urlpatterns = patterns('myproject.news.views',
33 227
         (r'^/articles/(?P<year>\d{4})/$', 'year_archive'),
34 228
         (r'^/articles/(?P<year>\d{4})/(?P<month>\d{2})/$', 'month_archive'),
35 229
         (r'^/articles/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d+)/$', 'article_detail'),
36 230
     )
37 231
 
38  
-.. admonition:: Note
39  
-
40  
-    More precisely, the actual view function used is ``prefix + "." +
41  
-    function_name``. The trailing "dot" does not need to be put in the prefix.
  232
+Note that you don't put a trailing dot (``"."``) in the prefix. Django puts
  233
+that in automatically.
42 234
 
43 235
 Including other URLconfs
44 236
 ========================
45 237
 
46  
-You can also "include" other URLconf modules at any point along the path. This
47  
-essentially "roots" a set of URLs below other ones.  This is most often used
48  
-for a site's "base" URLconf; the ``ROOT_URLCONF`` setting points to a urlconf
49  
-module that will be used for the entire site. Here's the URLconf for the
50  
-`Django website`_ itself. It includes a number of other URLconfs::
  238
+At any point, your ``urlpatterns`` can "include" other URLconf modules. This
  239
+essentially "roots" a set of URLs below other ones.
  240
+
  241
+For example, here's the URLconf for the `Django website`_ itself. It includes a
  242
+number of other URLconfs::
51 243
 
52 244
     from django.conf.urls.defaults import *
53 245
 
@@ -70,6 +262,7 @@ URLconfs, so the following example is valid::
70 262
     urlpatterns = patterns('foo.views'
71 263
         (r'^$', 'blog.index'),
72 264
         (r'^archive/$', 'blog.archive'),
  265
+    )
73 266
 
74 267
 In the above example, the captured ``"username"`` variable is passed to the
75 268
 included URLconf, as expected.
@@ -79,11 +272,25 @@ included URLconf, as expected.
79 272
 Passing extra options to view functions
80 273
 =======================================
81 274
 
82  
-There are two ways of passing arguments into your view functions: named captures
83  
-from the regex (which you've already seen) and the optional third element
84  
-in URLconf tuples. This third element can be a dictionary of extra keyword
85  
-arguments that will be passed to the view function::
  275
+URLconfs have a hook that lets you pass extra arguments to your view functions,
  276
+as a Python dictionary.
  277
+
  278
+Any URLconf tuple can have an optional third element, which should be a
  279
+dictionary of extra keyword arguments to pass to the view function.
  280
+
  281
+For example::
86 282
 
87  
-    urlpatterns = patterns('myproject.news.views.articles',
88  
-        (r'^/articles/(?P<year>\d{4})/$', 'year_archive', {key: value, key2: value2}),
  283
+    urlpatterns = patterns('blog.views',
  284
+        (r'^/blog/(?P<year>\d{4})/$', 'year_archive', {'foo': 'bar'}),
89 285
     )
  286
+
  287
+In this example, for a request to ``/blog/2005/``, Django will call the
  288
+``blog.views.year_archive()`` view, passing it these keyword arguments::
  289
+
  290
+    year='2005', foo='bar'
  291
+
  292
+This technique is used in `generic views`_ and in the `syndication framework`_
  293
+to pass metadata and options to views.
  294
+
  295
+.. _generic views: http://www.djangoproject.com/documentation/generic_views/
  296
+.. _syndication framework: http://www.djangoproject.com/documentation/syndication/

0 notes on commit f125fb0

Please sign in to comment.
Something went wrong with that request. Please try again.