Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Refactored URL mapping documentation.

Reorganized topic document so it introduces concepts form simple to more
complex. Moved reference parts to their own documents.
  • Loading branch information...
commit b6b8a3f66b5cf4f00bd7ce668ac04f21bb73e0b9 1 parent 8a22166
@ramiro ramiro authored
View
4 docs/ref/index.txt
@@ -6,7 +6,7 @@ API Reference
:maxdepth: 1
authbackends
- class-based-views/index
+ class-based-views/index
clickjacking
contrib/index
databases
@@ -22,5 +22,7 @@ API Reference
signals
templates/index
unicode
+ urlresolvers
+ urls
utils
validators
View
204 docs/ref/urlresolvers.txt
@@ -0,0 +1,204 @@
+==============================================
+``django.core.urlresolvers`` utility functions
+==============================================
+
+.. module:: django.core.urlresolvers
+
+reverse()
+---------
+
+If you need to use something similar to the :ttag:`url` template tag in
+your code, Django provides the following function (in the
+:mod:`django.core.urlresolvers` module):
+
+.. function:: reverse(viewname, [urlconf=None, args=None, kwargs=None, current_app=None])
+
+``viewname`` is either the function name (either a function reference, or the
+string version of the name, if you used that form in ``urlpatterns``) or the
+:ref:`URL pattern name <naming-url-patterns>`. Normally, you won't need to
+worry about the ``urlconf`` parameter and will only pass in the positional and
+keyword arguments to use in the URL matching. For example::
+
+ from django.core.urlresolvers import reverse
+
+ def myview(request):
+ return HttpResponseRedirect(reverse('arch-summary', args=[1945]))
+
+The ``reverse()`` function can reverse a large variety of regular expression
+patterns for URLs, but not every possible one. The main restriction at the
+moment is that the pattern cannot contain alternative choices using the
+vertical bar (``"|"``) character. You can quite happily use such patterns for
+matching against incoming URLs and sending them off to views, but you cannot
+reverse such patterns.
+
+The ``current_app`` argument allows you to provide a hint to the resolver
+indicating the application to which the currently executing view belongs.
+This ``current_app`` argument is used as a hint to resolve application
+namespaces into URLs on specific application instances, according to the
+:ref:`namespaced URL resolution strategy <topics-http-reversing-url-namespaces>`.
+
+You can use ``kwargs`` instead of ``args``. For example::
+
+ >>> reverse('admin:app_list', kwargs={'app_label': 'auth'})
+ '/admin/auth/'
+
+``args`` and ``kwargs`` cannot be passed to ``reverse()`` at the same time.
+
+.. admonition:: Make sure your views are all correct.
+
+ As part of working out which URL names map to which patterns, the
+ ``reverse()`` function has to import all of your URLconf files and examine
+ the name of each view. This involves importing each view function. If
+ there are *any* errors whilst importing any of your view functions, it
+ will cause ``reverse()`` to raise an error, even if that view function is
+ not the one you are trying to reverse.
+
+ Make sure that any views you reference in your URLconf files exist and can
+ be imported correctly. Do not include lines that reference views you
+ haven't written yet, because those views will not be importable.
+
+.. note::
+
+ The string returned by :meth:`~django.core.urlresolvers.reverse` is already
+ :ref:`urlquoted <uri-and-iri-handling>`. For example::
+
+ >>> reverse('cities', args=[u'Orléans'])
+ '.../Orl%C3%A9ans/'
+
+ Applying further encoding (such as :meth:`~django.utils.http.urlquote` or
+ ``urllib.quote``) to the output of :meth:`~django.core.urlresolvers.reverse`
+ may produce undesirable results.
+
+reverse_lazy()
+--------------
+
+.. versionadded:: 1.4
+
+A lazily evaluated version of `reverse()`_.
+
+.. function:: reverse_lazy(viewname, [urlconf=None, args=None, kwargs=None, current_app=None])
+
+It is useful for when you need to use a URL reversal before your project's
+URLConf is loaded. Some common cases where this function is necessary are:
+
+* providing a reversed URL as the ``url`` attribute of a generic class-based
+ view.
+
+* providing a reversed URL to a decorator (such as the ``login_url`` argument
+ for the :func:`django.contrib.auth.decorators.permission_required`
+ decorator).
+
+* providing a reversed URL as a default value for a parameter in a function's
+ signature.
+
+resolve()
+---------
+
+The :func:`django.core.urlresolvers.resolve` function can be used for
+resolving URL paths to the corresponding view functions. It has the
+following signature:
+
+.. function:: resolve(path, urlconf=None)
+
+``path`` is the URL path you want to resolve. As with
+:func:`~django.core.urlresolvers.reverse`, you don't need to
+worry about the ``urlconf`` parameter. The function returns a
+:class:`ResolverMatch` object that allows you
+to access various meta-data about the resolved URL.
+
+If the URL does not resolve, the function raises an
+:class:`~django.http.Http404` exception.
+
+.. class:: ResolverMatch
+
+ .. attribute:: ResolverMatch.func
+
+ The view function that would be used to serve the URL
+
+ .. attribute:: ResolverMatch.args
+
+ The arguments that would be passed to the view function, as
+ parsed from the URL.
+
+ .. attribute:: ResolverMatch.kwargs
+
+ The keyword arguments that would be passed to the view
+ function, as parsed from the URL.
+
+ .. attribute:: ResolverMatch.url_name
+
+ The name of the URL pattern that matches the URL.
+
+ .. attribute:: ResolverMatch.app_name
+
+ The application namespace for the URL pattern that matches the
+ URL.
+
+ .. attribute:: ResolverMatch.namespace
+
+ The instance namespace for the URL pattern that matches the
+ URL.
+
+ .. attribute:: ResolverMatch.namespaces
+
+ The list of individual namespace components in the full
+ instance namespace for the URL pattern that matches the URL.
+ i.e., if the namespace is ``foo:bar``, then namespaces will be
+ ``['foo', 'bar']``.
+
+A :class:`ResolverMatch` object can then be interrogated to provide
+information about the URL pattern that matches a URL::
+
+ # Resolve a URL
+ match = resolve('/some/path/')
+ # Print the URL pattern that matches the URL
+ print(match.url_name)
+
+A :class:`ResolverMatch` object can also be assigned to a triple::
+
+ func, args, kwargs = resolve('/some/path/')
+
+One possible use of :func:`~django.core.urlresolvers.resolve` would be to test
+whether a view would raise a ``Http404`` error before redirecting to it::
+
+ from urlparse import urlparse
+ from django.core.urlresolvers import resolve
+ from django.http import HttpResponseRedirect, Http404
+
+ def myview(request):
+ next = request.META.get('HTTP_REFERER', None) or '/'
+ response = HttpResponseRedirect(next)
+
+ # modify the request and response as required, e.g. change locale
+ # and set corresponding locale cookie
+
+ view, args, kwargs = resolve(urlparse(next)[2])
+ kwargs['request'] = request
+ try:
+ view(*args, **kwargs)
+ except Http404:
+ return HttpResponseRedirect('/')
+ return response
+
+
+permalink()
+-----------
+
+The :func:`django.db.models.permalink` decorator is useful for writing short
+methods that return a full URL path. For example, a model's
+``get_absolute_url()`` method. See :func:`django.db.models.permalink` for more.
+
+get_script_prefix()
+-------------------
+
+.. function:: get_script_prefix()
+
+Normally, you should always use :func:`~django.core.urlresolvers.reverse` or
+:func:`~django.db.models.permalink` to define URLs within your application.
+However, if your application constructs part of the URL hierarchy itself, you
+may occasionally need to generate URLs. In that case, you need to be able to
+find the base URL of the Django project within its Web server
+(normally, :func:`~django.core.urlresolvers.reverse` takes care of this for
+you). In that case, you can call ``get_script_prefix()``, which will return the
+script prefix portion of the URL for your Django project. If your Django
+project is at the root of its Web server, this is always ``"/"``.
View
139 docs/ref/urls.txt
@@ -0,0 +1,139 @@
+======================================
+``django.conf.urls`` utility functions
+======================================
+
+.. module:: django.conf.urls
+
+.. versionchanged:: 1.4
+ Starting with Django 1.4 functions ``patterns``, ``url``, ``include`` plus
+ the ``handler*`` symbols described below live in the ``django.conf.urls``
+ module.
+
+ Until Django 1.3 they were located in ``django.conf.urls.defaults``. You
+ still can import them from there but it will be removed in Django 1.6.
+
+patterns()
+----------
+
+.. function:: patterns(prefix, pattern_description, ...)
+
+A function that takes a prefix, and an arbitrary number of URL patterns, and
+returns a list of URL patterns in the format Django needs.
+
+The first argument to ``patterns()`` is a string ``prefix``. See
+:ref:`The view prefix <urlpatterns-view-prefix>`.
+
+The remaining arguments should be tuples in this format::
+
+ (regular expression, Python callback function [, optional_dictionary [, optional_name]])
+
+The ``optional_dictionary`` and ``optional_name`` parameters are described in
+:ref:`Passing extra options to view functions <views-extra-options>`.
+
+.. note::
+ Because `patterns()` is a function call, it accepts a maximum of 255
+ arguments (URL patterns, in this case). This is a limit for all Python
+ function calls. This is rarely a problem in practice, because you'll
+ typically structure your URL patterns modularly by using `include()`
+ sections. However, on the off-chance you do hit the 255-argument limit,
+ realize that `patterns()` returns a Python list, so you can split up the
+ construction of the list.
+
+ ::
+
+ urlpatterns = patterns('',
+ ...
+ )
+ urlpatterns += patterns('',
+ ...
+ )
+
+ Python lists have unlimited size, so there's no limit to how many URL
+ patterns you can construct. The only limit is that you can only create 254
+ at a time (the 255th argument is the initial prefix argument).
+
+url()
+-----
+
+.. function:: url(regex, view, kwargs=None, name=None, prefix='')
+
+You can use the ``url()`` function, instead of a tuple, as an argument to
+``patterns()``. This is convenient if you want to specify a name without the
+optional extra arguments dictionary. For example::
+
+ urlpatterns = patterns('',
+ url(r'^index/$', index_view, name="main-view"),
+ ...
+ )
+
+This function takes five arguments, most of which are optional::
+
+ url(regex, view, kwargs=None, name=None, prefix='')
+
+See :ref:`Naming URL patterns <naming-url-patterns>` for why the ``name``
+parameter is useful.
+
+The ``prefix`` parameter has the same meaning as the first argument to
+``patterns()`` and is only relevant when you're passing a string as the
+``view`` parameter.
+
+include()
+---------
+
+.. function:: include(<module or pattern_list>)
+
+A function that takes a full Python import path to another URLconf module that
+should be "included" in this place.
+
+:func:`include` also accepts as an argument an iterable that returns URL
+patterns.
+
+See :ref:`Including other URLconfs <including-other-urlconfs>`.
+
+handler403
+----------
+
+.. data:: handler403
+
+A callable, or a string representing the full Python import path to the view
+that should be called if the user doesn't have the permissions required to
+access a resource.
+
+By default, this is ``'django.views.defaults.permission_denied'``. That default
+value should suffice.
+
+See the documentation about :ref:`the 403 (HTTP Forbidden) view
+<http_forbidden_view>` for more information.
+
+.. versionadded:: 1.4
+ ``handler403`` is new in Django 1.4.
+
+handler404
+----------
+
+.. data:: handler404
+
+A callable, or a string representing the full Python import path to the view
+that should be called if none of the URL patterns match.
+
+By default, this is ``'django.views.defaults.page_not_found'``. That default
+value should suffice.
+
+See the documentation about :ref:`the 404 (HTTP Not Found) view
+<http_not_found_view>` for more information.
+
+handler500
+----------
+
+.. data:: handler500
+
+A callable, or a string representing the full Python import path to the view
+that should be called in case of server errors. Server errors happen when you
+have runtime errors in view code.
+
+By default, this is ``'django.views.defaults.server_error'``. That default
+value should suffice.
+
+See the documentation about :ref:`the 500 (HTTP Internal Server Error) view
+<http_internal_server_error_view>` for more information.
+
View
483 docs/topics/http/urls.txt
@@ -2,8 +2,6 @@
URL dispatcher
==============
-.. module:: django.core.urlresolvers
-
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.
@@ -160,7 +158,8 @@ vs. non-named groups in a regular expression:
2. Otherwise, it will pass all non-named arguments as positional arguments.
-In both cases, any extra keyword arguments that have been given as per `Passing extra options to view functions`_ (below) will also be passed to the view.
+In both cases, any extra keyword arguments that have been given as per `Passing
+extra options to view functions`_ (below) will also be passed to the view.
What the URLconf searches against
=================================
@@ -215,7 +214,6 @@ Performance
Each regular expression in a ``urlpatterns`` is compiled the first time it's
accessed. This makes the system blazingly fast.
-
Syntax of the urlpatterns variable
==================================
@@ -223,154 +221,35 @@ Syntax of the urlpatterns variable
:func:`django.conf.urls.patterns`. Always use ``patterns()`` to create
the ``urlpatterns`` variable.
-``django.conf.urls`` utility functions
-======================================
-
-.. module:: django.conf.urls
-
-.. deprecated:: 1.4
- Starting with Django 1.4 functions ``patterns``, ``url``, ``include`` plus
- the ``handler*`` symbols described below live in the ``django.conf.urls``
- module.
-
- Until Django 1.3 they were located in ``django.conf.urls.defaults``. You
- still can import them from there but it will be removed in Django 1.6.
-
-patterns
---------
-
-.. function:: patterns(prefix, pattern_description, ...)
-
-A function that takes a prefix, and an arbitrary number of URL patterns, and
-returns a list of URL patterns in the format Django needs.
-
-The first argument to ``patterns()`` is a string ``prefix``. See
-`The view prefix`_ below.
-
-The remaining arguments should be tuples in this format::
-
- (regular expression, Python callback function [, optional_dictionary [, optional_name]])
-
-The ``optional_dictionary`` and ``optional_name`` parameters are described in
-`Passing extra options to view functions`_ below.
-
-.. note::
- Because `patterns()` is a function call, it accepts a maximum of 255
- arguments (URL patterns, in this case). This is a limit for all Python
- function calls. This is rarely a problem in practice, because you'll
- typically structure your URL patterns modularly by using `include()`
- sections. However, on the off-chance you do hit the 255-argument limit,
- realize that `patterns()` returns a Python list, so you can split up the
- construction of the list.
-
- ::
-
- urlpatterns = patterns('',
- ...
- )
- urlpatterns += patterns('',
- ...
- )
-
- Python lists have unlimited size, so there's no limit to how many URL
- patterns you can construct. The only limit is that you can only create 254
- at a time (the 255th argument is the initial prefix argument).
-
-url
----
-
-.. function:: url(regex, view, kwargs=None, name=None, prefix='')
-
-You can use the ``url()`` function, instead of a tuple, as an argument to
-``patterns()``. This is convenient if you want to specify a name without the
-optional extra arguments dictionary. For example::
-
- urlpatterns = patterns('',
- url(r'^index/$', index_view, name="main-view"),
- ...
- )
-
-This function takes five arguments, most of which are optional::
-
- url(regex, view, kwargs=None, name=None, prefix='')
-
-See `Naming URL patterns`_ for why the ``name`` parameter is useful.
-
-The ``prefix`` parameter has the same meaning as the first argument to
-``patterns()`` and is only relevant when you're passing a string as the
-``view`` parameter.
-
-include
--------
-
-.. function:: include(<module or pattern_list>)
-
-A function that takes a full Python import path to another URLconf module that
-should be "included" in this place.
-
-:func:`include` also accepts as an argument an iterable that returns URL
-patterns.
-
-See `Including other URLconfs`_ below.
-
Error handling
==============
When Django can't find a regex matching the requested URL, or when an
-exception is raised, Django will invoke an error-handling view. The
-views to use for these cases are specified by three variables which can
-be set in your root URLconf. Setting these variables in any other
-URLconf will have no effect.
+exception is raised, Django will invoke an error-handling view.
-See the documentation on :ref:`customizing error views
-<customizing-error-views>` for more details.
+The views to use for these cases are specified by three variables. Their
+default values should suffice for most projects, but further customization is
+possible by assigning values to them.
-handler403
-----------
+See the documentation on :ref:`customizing error views
+<customizing-error-views>` for the full details.
-.. data:: handler403
+Such values can be set in your root URLconf. Setting these variables in any
+other URLconf will have no effect.
-A callable, or a string representing the full Python import path to the view
-that should be called if the user doesn't have the permissions required to
-access a resource.
+Values must be callables, or strings representing the full Python import path
+to the view that should be called to handle the error condition at hand.
-By default, this is ``'django.views.defaults.permission_denied'``. That default
-value should suffice.
+The variables are:
-See the documentation about :ref:`the 403 (HTTP Forbidden) view
-<http_forbidden_view>` for more information.
+* ``handler404`` -- See :data:`django.conf.urls.handler404`.
+* ``handler500`` -- See :data:`django.conf.urls.handler500`.
+* ``handler403`` -- See :data:`django.conf.urls.handler403`.
.. versionadded:: 1.4
``handler403`` is new in Django 1.4.
-handler404
-----------
-
-.. data:: handler404
-
-A callable, or a string representing the full Python import path to the view
-that should be called if none of the URL patterns match.
-
-By default, this is ``'django.views.defaults.page_not_found'``. That default
-value should suffice.
-
-See the documentation about :ref:`the 404 (HTTP Not Found) view
-<http_not_found_view>` for more information.
-
-handler500
-----------
-
-.. data:: handler500
-
-A callable, or a string representing the full Python import path to the view
-that should be called in case of server errors. Server errors happen when you
-have runtime errors in view code.
-
-By default, this is ``'django.views.defaults.server_error'``. That default
-value should suffice.
-
-See the documentation about :ref:`the 500 (HTTP Internal Server Error) view
-<http_internal_server_error_view>` for more information.
+.. _urlpatterns-view-prefix:
The view prefix
===============
@@ -437,6 +316,8 @@ New::
(r'^tag/(?P<tag>\w+)/$', 'tag'),
)
+.. _including-other-urlconfs:
+
Including other URLconfs
========================
@@ -459,13 +340,14 @@ itself. It includes a number of other URLconfs::
Note that the regular expressions in this example don't have a ``$``
(end-of-string match character) but do include a trailing slash. Whenever
-Django encounters ``include()``, it chops off whatever part of the URL matched
-up to that point and sends the remaining string to the included URLconf for
-further processing.
+Django encounters ``include()`` (:func:`django.conf.urls.include()`), it chops
+off whatever part of the URL matched up to that point and sends the remaining
+string to the included URLconf for further processing.
Another possibility is to include additional URL patterns not by specifying the
-URLconf Python module defining them as the `include`_ argument but by using
-directly the pattern list as returned by `patterns`_ instead. For example::
+URLconf Python module defining them as the ``include()`` argument but by using
+directly the pattern list as returned by :func:`~django.conf.urls.patterns`
+instead. For example::
from django.conf.urls import patterns, url, include
@@ -510,57 +392,7 @@ the following example is valid::
In the above example, the captured ``"username"`` variable is passed to the
included URLconf, as expected.
-.. _topics-http-defining-url-namespaces:
-
-Defining URL namespaces
------------------------
-
-When you need to deploy multiple instances of a single application, it can be
-helpful to be able to differentiate between instances. This is especially
-important when using :ref:`named URL patterns <naming-url-patterns>`, since
-multiple instances of a single application will share named URLs. Namespaces
-provide a way to tell these named URLs apart.
-
-A URL namespace comes in two parts, both of which are strings:
-
-* An **application namespace**. This describes the name of the application
- that is being deployed. Every instance of a single application will have
- the same application namespace. For example, Django's admin application
- has the somewhat predictable application namespace of ``admin``.
-
-* An **instance namespace**. This identifies a specific instance of an
- application. Instance namespaces should be unique across your entire
- project. However, an instance namespace can be the same as the
- application namespace. This is used to specify a default instance of an
- application. For example, the default Django Admin instance has an
- instance namespace of ``admin``.
-
-URL Namespaces can be specified in two ways.
-
-Firstly, you can provide the application and instance namespace as arguments
-to ``include()`` when you construct your URL patterns. For example,::
-
- (r'^help/', include('apps.help.urls', namespace='foo', app_name='bar')),
-
-This will include the URLs defined in ``apps.help.urls`` into the application
-namespace ``bar``, with the instance namespace ``foo``.
-
-Secondly, you can include an object that contains embedded namespace data. If
-you ``include()`` a ``patterns`` object, that object will be added to the
-global namespace. However, you can also ``include()`` an object that contains
-a 3-tuple containing::
-
- (<patterns object>, <application namespace>, <instance namespace>)
-
-This will include the nominated URL patterns into the given application and
-instance namespace. For example, the ``urls`` attribute of Django's
-:class:`~django.contrib.admin.AdminSite` object returns a 3-tuple that contains
-all the patterns in an admin site, plus the name of the admin instance, and the
-application namespace ``admin``.
-
-Once you have defined namespaced URLs, you can reverse them. For details on
-reversing namespaced urls, see the documentation on :ref:`reversing namespaced
-URLs <topics-http-reversing-url-namespaces>`.
+.. _views-extra-options:
Passing extra options to view functions
=======================================
@@ -698,10 +530,10 @@ view::
)
This is completely valid, but it leads to problems when you try to do reverse
-URL matching (through the ``permalink()`` decorator or the :ttag:`url` template
-tag). Continuing this example, if you wanted to retrieve the URL for the
-``archive`` view, Django's reverse URL matcher would get confused, because *two*
-URL patterns point at that view.
+URL matching (through the :func:`~django.db.models.permalink` decorator or the
+:ttag:`url` template tag). Continuing this example, if you wanted to retrieve
+the URL for the ``archive`` view, Django's reverse URL matcher would get
+confused, because *two* URL patterns point at that view.
To solve this problem, Django supports **named URL patterns**. That is, you can
give a name to a URL pattern in order to distinguish it from other patterns
@@ -741,10 +573,36 @@ not restricted to valid Python names.
name, will decrease the chances of collision. We recommend something like
``myapp-comment`` instead of ``comment``.
-.. _topics-http-reversing-url-namespaces:
+.. _topics-http-defining-url-namespaces:
URL namespaces
---------------
+==============
+
+Introduction
+------------
+
+When you need to deploy multiple instances of a single application, it can be
+helpful to be able to differentiate between instances. This is especially
+important when using :ref:`named URL patterns <naming-url-patterns>`, since
+multiple instances of a single application will share named URLs. Namespaces
+provide a way to tell these named URLs apart.
+
+A URL namespace comes in two parts, both of which are strings:
+
+.. glossary::
+
+ application namespace
+ This describes the name of the application that is being deployed. Every
+ instance of a single application will have the same application namespace.
+ For example, Django's admin application has the somewhat predictable
+ application namespace of ``admin``.
+
+ instance namespace
+ This identifies a specific instance of an application. Instance namespaces
+ should be unique across your entire project. However, an instance namespace
+ can be the same as the application namespace. This is used to specify a
+ default instance of an application. For example, the default Django Admin
+ instance has an instance namespace of ``admin``.
Namespaced URLs are specified using the ``:`` operator. For example, the main
index page of the admin application is referenced using ``admin:index``. This
@@ -754,6 +612,11 @@ Namespaces can also be nested. The named URL ``foo:bar:whiz`` would look for
a pattern named ``whiz`` in the namespace ``bar`` that is itself defined within
the top-level namespace ``foo``.
+.. _topics-http-reversing-url-namespaces:
+
+Reversing namespaced URLs
+-------------------------
+
When given a namespaced URL (e.g. ``myapp:index``) to resolve, Django splits
the fully qualified name into parts, and then tries the following lookup:
@@ -787,6 +650,9 @@ If there are nested namespaces, these steps are repeated for each part of the
namespace until only the view name is unresolved. The view name will then be
resolved into a URL in the namespace that has been found.
+Example
+~~~~~~~
+
To show this resolution strategy in action, consider an example of two instances
of ``myapp``: one called ``foo``, and one called ``bar``. ``myapp`` has a main
index page with a URL named `index`. Using this setup, the following lookups are
@@ -818,209 +684,28 @@ following would happen:
* ``foo:index`` will again resolve to the index page of the instance ``foo``.
+URL namespaces and included URLconfs
+------------------------------------
-``django.core.urlresolvers`` utility functions
-==============================================
-
-.. currentmodule:: django.core.urlresolvers
-
-reverse()
----------
-
-If you need to use something similar to the :ttag:`url` template tag in
-your code, Django provides the following function (in the
-:mod:`django.core.urlresolvers` module):
-
-.. function:: reverse(viewname, [urlconf=None, args=None, kwargs=None, current_app=None])
-
-``viewname`` is either the function name (either a function reference, or the
-string version of the name, if you used that form in ``urlpatterns``) or the
-`URL pattern name`_. Normally, you won't need to worry about the
-``urlconf`` parameter and will only pass in the positional and keyword
-arguments to use in the URL matching. For example::
-
- from django.core.urlresolvers import reverse
-
- def myview(request):
- return HttpResponseRedirect(reverse('arch-summary', args=[1945]))
-
-.. _URL pattern name: `Naming URL patterns`_
-
-The ``reverse()`` function can reverse a large variety of regular expression
-patterns for URLs, but not every possible one. The main restriction at the
-moment is that the pattern cannot contain alternative choices using the
-vertical bar (``"|"``) character. You can quite happily use such patterns for
-matching against incoming URLs and sending them off to views, but you cannot
-reverse such patterns.
-
-The ``current_app`` argument allows you to provide a hint to the resolver
-indicating the application to which the currently executing view belongs.
-This ``current_app`` argument is used as a hint to resolve application
-namespaces into URLs on specific application instances, according to the
-:ref:`namespaced URL resolution strategy <topics-http-reversing-url-namespaces>`.
-
-You can use ``kwargs`` instead of ``args``. For example::
-
- >>> reverse('admin:app_list', kwargs={'app_label': 'auth'})
- '/admin/auth/'
-
-``args`` and ``kwargs`` cannot be passed to ``reverse()`` at the same time.
-
-.. admonition:: Make sure your views are all correct.
-
- As part of working out which URL names map to which patterns, the
- ``reverse()`` function has to import all of your URLconf files and examine
- the name of each view. This involves importing each view function. If
- there are *any* errors whilst importing any of your view functions, it
- will cause ``reverse()`` to raise an error, even if that view function is
- not the one you are trying to reverse.
-
- Make sure that any views you reference in your URLconf files exist and can
- be imported correctly. Do not include lines that reference views you
- haven't written yet, because those views will not be importable.
-
-.. note::
-
- The string returned by :meth:`~django.core.urlresolvers.reverse` is already
- :ref:`urlquoted <uri-and-iri-handling>`. For example::
-
- >>> reverse('cities', args=[u'Orléans'])
- '.../Orl%C3%A9ans/'
-
- Applying further encoding (such as :meth:`~django.utils.http.urlquote` or
- ``urllib.quote``) to the output of :meth:`~django.core.urlresolvers.reverse`
- may produce undesirable results.
-
-reverse_lazy()
---------------
-
-.. versionadded:: 1.4
-
-A lazily evaluated version of `reverse()`_.
-
-.. function:: reverse_lazy(viewname, [urlconf=None, args=None, kwargs=None, current_app=None])
-
-It is useful for when you need to use a URL reversal before your project's
-URLConf is loaded. Some common cases where this function is necessary are:
-
-* providing a reversed URL as the ``url`` attribute of a generic class-based
- view.
-
-* providing a reversed URL to a decorator (such as the ``login_url`` argument
- for the :func:`django.contrib.auth.decorators.permission_required`
- decorator).
-
-* providing a reversed URL as a default value for a parameter in a function's
- signature.
-
-resolve()
----------
+URL namespaces of included URLconfs can be specified in two ways.
-The :func:`django.core.urlresolvers.resolve` function can be used for
-resolving URL paths to the corresponding view functions. It has the
-following signature:
-
-.. function:: resolve(path, urlconf=None)
-
-``path`` is the URL path you want to resolve. As with
-:func:`~django.core.urlresolvers.reverse`, you don't need to
-worry about the ``urlconf`` parameter. The function returns a
-:class:`ResolverMatch` object that allows you
-to access various meta-data about the resolved URL.
-
-If the URL does not resolve, the function raises an
-:class:`~django.http.Http404` exception.
-
-.. class:: ResolverMatch
-
- .. attribute:: ResolverMatch.func
-
- The view function that would be used to serve the URL
-
- .. attribute:: ResolverMatch.args
-
- The arguments that would be passed to the view function, as
- parsed from the URL.
-
- .. attribute:: ResolverMatch.kwargs
-
- The keyword arguments that would be passed to the view
- function, as parsed from the URL.
-
- .. attribute:: ResolverMatch.url_name
-
- The name of the URL pattern that matches the URL.
-
- .. attribute:: ResolverMatch.app_name
-
- The application namespace for the URL pattern that matches the
- URL.
-
- .. attribute:: ResolverMatch.namespace
-
- The instance namespace for the URL pattern that matches the
- URL.
-
- .. attribute:: ResolverMatch.namespaces
-
- The list of individual namespace components in the full
- instance namespace for the URL pattern that matches the URL.
- i.e., if the namespace is ``foo:bar``, then namespaces will be
- ``['foo', 'bar']``.
-
-A :class:`ResolverMatch` object can then be interrogated to provide
-information about the URL pattern that matches a URL::
-
- # Resolve a URL
- match = resolve('/some/path/')
- # Print the URL pattern that matches the URL
- print(match.url_name)
-
-A :class:`ResolverMatch` object can also be assigned to a triple::
-
- func, args, kwargs = resolve('/some/path/')
-
-One possible use of :func:`~django.core.urlresolvers.resolve` would be to test
-whether a view would raise a ``Http404`` error before redirecting to it::
-
- from urlparse import urlparse
- from django.core.urlresolvers import resolve
- from django.http import HttpResponseRedirect, Http404
-
- def myview(request):
- next = request.META.get('HTTP_REFERER', None) or '/'
- response = HttpResponseRedirect(next)
-
- # modify the request and response as required, e.g. change locale
- # and set corresponding locale cookie
-
- view, args, kwargs = resolve(urlparse(next)[2])
- kwargs['request'] = request
- try:
- view(*args, **kwargs)
- except Http404:
- return HttpResponseRedirect('/')
- return response
+Firstly, you can provide the application and instance namespace as arguments
+to ``include()`` when you construct your URL patterns. For example,::
+ (r'^help/', include('apps.help.urls', namespace='foo', app_name='bar')),
-permalink()
------------
+This will include the URLs defined in ``apps.help.urls`` into the application
+namespace ``bar``, with the instance namespace ``foo``.
-The :func:`django.db.models.permalink` decorator is useful for writing short
-methods that return a full URL path. For example, a model's
-``get_absolute_url()`` method. See :func:`django.db.models.permalink` for more.
+Secondly, you can include an object that contains embedded namespace data. If
+you ``include()`` a ``patterns`` object, that object will be added to the
+global namespace. However, you can also ``include()`` an object that contains
+a 3-tuple containing::
-get_script_prefix()
--------------------
+ (<patterns object>, <application namespace>, <instance namespace>)
-.. function:: get_script_prefix()
-
-Normally, you should always use :func:`~django.core.urlresolvers.reverse` or
-:func:`~django.db.models.permalink` to define URLs within your application.
-However, if your application constructs part of the URL hierarchy itself, you
-may occasionally need to generate URLs. In that case, you need to be able to
-find the base URL of the Django project within its Web server
-(normally, :func:`~django.core.urlresolvers.reverse` takes care of this for
-you). In that case, you can call ``get_script_prefix()``, which will return the
-script prefix portion of the URL for your Django project. If your Django
-project is at the root of its Web server, this is always ``"/"``.
+This will include the nominated URL patterns into the given application and
+instance namespace. For example, the ``urls`` attribute of Django's
+:class:`~django.contrib.admin.AdminSite` object returns a 3-tuple that contains
+all the patterns in an admin site, plus the name of the admin instance, and the
+application namespace ``admin``.
Please sign in to comment.
Something went wrong with that request. Please try again.