Django

Code

Changeset 1291

Show
Ignore:
Timestamp:
11/19/05 12:20:30 (2 years ago)
Author:
adrian
Message:

Beefed up docs/url_dispatch.txt

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • django/trunk/docs/overview.txt

    r1219 r1291  
    163163 
    164164    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'), 
    168168    ) 
    169169 
     
    182182 
    183183For example, if a user requested the URL "/articles/2005/05/39323/", Django 
    184 would call the function ``myproject.news.views.articles.article_detail(request, 
     184would call the function ``myproject.news.views.article_detail(request, 
    185185year='2005', month='05', article_id='39323')``. 
    186186 
     
    281281 
    282282    * 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. 
    285285    * More sexy automatically-generated admin features -- this overview barely 
    286286      scratched the surface. 
  • django/trunk/docs/tutorial03.txt

    r1258 r1291  
    6161 
    6262For more on ``HTTPRequest`` objects, see the `request and response documentation`_. 
     63For more details on URLconfs, see the `URLconf documentation`_. 
    6364 
    6465When you ran ``django-admin.py startproject myproject`` at the beginning of 
     
    6869    ROOT_URLCONF = 'myproject.urls' 
    6970 
    70 Time for an example. Edit ``myproject/urls.py`` so it looks like 
    71 this:: 
     71Time for an example. Edit ``myproject/urls.py`` so it looks like this:: 
    7272 
    7373    from django.conf.urls.defaults import * 
     
    8989Finally, it calls that ``detail()`` function like so:: 
    9090 
    91     detail(request=<HttpRequest object>, poll_id=23
    92  
    93 The ``poll_id=23`` part comes from ``(?P<poll_id>\d+)``. Using 
     91    detail(request=<HttpRequest object>, poll_id='23'
     92 
     93The ``poll_id='23'`` part comes from ``(?P<poll_id>\d+)``. Using 
    9494``(?P<name>pattern)`` "captures" the text matched by ``pattern`` and sends it 
    9595as a keyword argument to the view function. 
     
    104104But, don't do that. It's silly. 
    105105 
     106Note that these regular expressions do not search GET and POST parameters, or 
     107the domain name. For example, in a request to ``http://www.example.com/myapp/``, 
     108the URLconf will look for ``/myapp/``. In a request to 
     109``http://www.example.com/myapp/?page=3``, the URLconf will look for ``/myapp/``. 
     110 
    106111If you need help with regular expressions, see `Wikipedia's entry`_ and the 
    107112`Python documentation`_. Also, the O'Reilly book "Mastering Regular 
     
    114119.. _Python documentation: http://www.python.org/doc/current/lib/module-re.html 
    115120.. _request and response documentation: http://www.djangoproject.com/documentation/request_response/ 
     121.. _URLconf documentation: http://www.djangoproject.com/documentation/url_dispatch/ 
    116122 
    117123Write your first view 
  • django/trunk/docs/url_dispatch.txt

    r1166 r1291  
    33============== 
    44 
    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. 
    8  
    9 See `the Django overview`_ for a quick introduction to URL configurations; this 
    10 document will continue from there. 
    11  
    12 .. _`the Django overview`: http://www.djangoproject.com/documentation/overview/#design-your-urls 
     5A clean, elegant URL scheme is an important detail in a high-quality Web 
     6application. Django lets you design URLs however you want, with no framework 
     7limitations. 
     8 
     9There's no ``.php`` or ``.cgi`` required, and certainly none of that 
     10``0,2097,1-1-1928,00`` nonsense. 
     11 
     12See `Cool URIs don't change`_, by World Wide Web creator Tim Berners-Lee, for 
     13excellent arguments on why URLs should be clean and usable. 
     14 
     15.. _http://www.w3.org/Provider/Style/URI: Cool URIs don't change 
     16 
     17Overview 
     18======== 
     19 
     20To design URLs for an app, you create a Python module informally called a 
     21**URLconf** (URL configuration). This module is pure Python code and 
     22is a simple mapping between URL patterns (as simple regular expressions) to 
     23Python callback functions (your views). 
     24 
     25This mapping can be as short or as long as needed. It can reference other 
     26mappings. And, because it's pure Python code, it can be constructed 
     27dynamically. 
     28 
     29How Django processes a request 
     30============================== 
     31 
     32When a user requests a page from your Django-powered site, this is the 
     33algorithm 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 
     51Example 
     52======= 
     53 
     54Here'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 
     65Notes: 
     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 
     78Examples: 
     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 
     101What the URLconf searches against 
     102================================= 
     103 
     104The URLconf searches against the requested URL, as a normal Python string. This 
     105does not include GET or POST parameters, or the domain name. 
     106 
     107For example, in a request to ``http://www.example.com/myapp/``, the URLconf 
     108will look for ``/myapp/``. 
     109 
     110In a request to ``http://www.example.com/myapp/?page=3``, the URLconf will look 
     111for ``/myapp/``. 
     112 
     113Syntax 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 
     118the ``urlpatterns`` variable. 
     119 
     120Convention is to use ``from django.conf.urls.defaults import *`` at the top of 
     121your URLconf. This gives your module access to these objects: 
     122 
     123patterns 
     124-------- 
     125 
     126A function that takes a prefix an arbitrary number of URL patterns and returns 
     127a list of URL patterns in the format Django needs. 
     128 
     129The first argument to ``patterns()`` is a string ``prefix``. See 
     130"The view prefix" below. 
     131 
     132The 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 
     139handler404 
     140---------- 
     141 
     142A string representing the full Python import path to the view that should be 
     143called if none of the URL patterns match. 
     144 
     145By default, this is ``'django.views.defaults.page_not_found'``. That default 
     146value should suffice. 
     147 
     148handler500 
     149---------- 
     150 
     151A string representing the full Python import path to the view that should be 
     152called in case of server errors. Server errors happen when you have runtime 
     153errors in view code. 
     154 
     155By default, this is ``'django.views.defaults.server_error'``. That default 
     156value should suffice. 
     157 
     158include 
     159------- 
     160 
     161A function that takes a full Python import path to another URLconf that should 
     162be "included" in this place. See "Including other URLconfs" below. 
     163 
     164Notes on capturing text in URLs 
     165=============================== 
     166 
     167Each captured argument is sent to the view as a plain Python string, regardless 
     168of what sort of match the regular expression makes. For example, in this 
     169URLconf:: 
     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 
     174an integer, even though the ``\d{4}`` will only match integer strings. 
     175 
     176A convenient trick is to specify default parameters for your views' arguments. 
     177Here'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 
     189In 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 
     191URL. If the first pattern matches, the ``page()`` function will use its 
     192default argument for ``num``, ``"1"``. If the second pattern matches, 
     193``page()`` will use whatever ``num`` value was captured by the regex. 
     194 
     195Performance 
     196=========== 
     197 
     198Each regular expression in a ``urlpatterns`` is compiled the first time it's 
     199accessed. This makes the system blazingly fast. 
    13200 
    14201The view prefix 
    15202=============== 
    16203 
    17 Here's the example from that overview:: 
    18  
    19     from django.conf.urls.defaults import * 
    20  
    21     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'), 
    25     ) 
    26  
    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:: 
    31  
    32     urlpatterns = patterns('myproject.news.views.articles', 
     204You can specify a common prefix in your ``patterns()`` call, to cut down on 
     205code duplication. 
     206 
     207Here's the example URLconf from the `Django overview`_:: 
     208 
     209    from django.conf.urls.defaults import * 
     210 
     211    urlpatterns = patterns('', 
     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'), 
     215    ) 
     216 
     217In this example, each view has a common prefix -- ``"myproject.news.views"``. 
     218Instead of typing that out for each entry in ``urlpatterns``, you can use the 
     219first argument to the ``patterns()`` function to specify a prefix to apply to 
     220each view function. 
     221 
     222With this in mind, the above example can be written more concisely as:: 
     223 
     224    from django.conf.urls.defaults import * 
     225 
     226    urlpatterns = patterns('myproject.news.views', 
    33227        (r'^/articles/(?P<year>\d{4})/$', 'year_archive'), 
    34228        (r'^/articles/(?P<year>\d{4})/(?P<month>\d{2})/$', 'month_archive'), 
     
    36230    ) 
    37231 
    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. 
     232Note that you don't put a trailing dot (``"."``) in the prefix. Django puts 
     233that in automatically. 
    42234 
    43235Including other URLconfs 
    44236======================== 
    45237 
    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:: 
     238At any point, your ``urlpatterns`` can "include" other URLconf modules. This 
     239essentially "roots" a set of URLs below other ones. 
     240 
     241For example, here's the URLconf for the `Django website`_ itself. It includes a 
     242number of other URLconfs:: 
    51243 
    52244    from django.conf.urls.defaults import * 
     
    71263        (r'^$', 'blog.index'), 
    72264        (r'^archive/$', 'blog.archive'), 
     265    ) 
    73266 
    74267In the above example, the captured ``"username"`` variable is passed to the 
     
    80273======================================= 
    81274 
    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:: 
    86  
    87     urlpatterns = patterns('myproject.news.views.articles', 
    88         (r'^/articles/(?P<year>\d{4})/$', 'year_archive', {key: value, key2: value2}), 
    89     ) 
     275URLconfs have a hook that lets you pass extra arguments to your view functions, 
     276as a Python dictionary. 
     277 
     278Any URLconf tuple can have an optional third element, which should be a 
     279dictionary of extra keyword arguments to pass to the view function. 
     280 
     281For example:: 
     282 
     283    urlpatterns = patterns('blog.views', 
     284        (r'^/blog/(?P<year>\d{4})/$', 'year_archive', {'foo': 'bar'}), 
     285    ) 
     286 
     287In 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 
     292This technique is used in `generic views`_ and in the `syndication framework`_ 
     293to 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/