django.urls utility functions¶
If you need to use something similar to the url template tag in your code, Django provides the following function:
reverse ( viewname , urlconf = None , args = None , kwargs = None , current_app = None ) ¶
viewname can be a URL pattern name or the callable view object. For example, given the following url :
you can use any of the following to reverse the URL:
If the URL accepts arguments, you may pass them in args . For example:
You can also pass kwargs instead of args . For example:
args and kwargs cannot be passed to reverse() at the same time.
If no match can be made, reverse() raises a NoReverseMatch exception.
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 namespaced URL resolution strategy .
The urlconf argument is the URLconf module containing the URL patterns to use for reversing. By default, the root URLconf for the current thread is used.
The string returned by reverse() is already urlquoted . For example:
Applying further encoding (such as urllib.parse.quote() ) to the output of reverse() may produce undesirable results.
reverse_lazy() ¶
A lazily evaluated version of reverse().
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 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 resolve() function can be used for resolving URL paths to the corresponding view functions. It has the following signature:
resolve ( path , urlconf = None ) ¶
path is the URL path you want to resolve. As with reverse() , you don’t need to worry about the urlconf parameter. The function returns a ResolverMatch object that allows you to access various metadata about the resolved URL.
If the URL does not resolve, the function raises a Resolver404 exception (a subclass of Http404 ) .
class ResolverMatch ¶ func ¶
The view function that would be used to serve the URL
The arguments that would be passed to the view function, as parsed from the URL.
All keyword arguments that would be passed to the view function, i.e. captured_kwargs and extra_kwargs .
The captured keyword arguments that would be passed to the view function, as parsed from the URL.
The additional keyword arguments that would be passed to the view function.
The name of the URL pattern that matches the URL.
The route of the matching URL pattern.
For example, if path(‘users/<id>/’, . ) is the matching pattern, route will contain ‘users/<id>/’ .
The list of URL patterns tried before the URL either matched one or exhausted available patterns.
The application namespace for the URL pattern that matches the URL.
The list of individual namespace components in the full application namespace for the URL pattern that matches the URL. For example, if the app_name is ‘foo:bar’ , then app_names will be [‘foo’, ‘bar’] .
The instance namespace for the URL pattern that matches the URL.
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’] .
The name of the view that matches the URL, including the namespace if there is one.
A ResolverMatch object can then be interrogated to provide information about the URL pattern that matches a URL:
A ResolverMatch object can also be assigned to a triple:
One possible use of resolve() would be to test whether a view would raise a Http404 error before redirecting to it:
get_script_prefix() ¶
Normally, you should always use reverse() 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, 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 "/" .
Вспомогательные функции django.urls ¶
Если вам нужно использовать в своем коде что-то похожее на тег шаблона url , Django предоставляет следующую функцию:
reverse ( viewname , urlconf = None , args = None , kwargs = None , current_app = None ) [исходный код] ¶
viewname может быть URL pattern name или вызываемым объектом представления. Например, учитывая следующее url :
вы можете использовать любой из следующих способов, чтобы изменить URL:
Если URL принимает аргументы, вы можете передать их в формате args . Например:
Вы также можете передать kwargs вместо args . Например:
args и kwargs не могут быть переданы в reverse() одновременно.
Если совпадение невозможно, reverse() вызывает исключение NoReverseMatch .
Функция reverse() может отменить большое количество шаблонов регулярных выражений для URL, но не все возможные. Основным ограничением на данный момент является то, что шаблон не может содержать альтернативные варианты с использованием символа вертикальной черты ( "|" ). Вы вполне можете использовать такие шаблоны для сопоставления с входящими URL и отправки их в представления, но вы не можете обратить такие шаблоны.
Аргумент current_app позволяет вам предоставить подсказку преобразователю, указывающую на приложение, к которому принадлежит текущее выполняющееся представление. Этот аргумент current_app используется в качестве подсказки для преобразования пространств имен приложений в URL-адреса конкретных экземпляров приложений в соответствии с namespaced URL resolution strategy .
Аргумент urlconf представляет собой модуль URLconf, содержащий шаблоны URL, которые следует использовать для реверсирования. По умолчанию используется корневой URLconf для текущего потока.
Строка, возвращаемая reverse() , уже является urlquoted . Например:
Применение дальнейшего кодирования (например, urllib.parse.quote() ) к выходу reverse() может привести к нежелательным результатам.
reverse_lazy() ¶
Лениво оцениваемая версия reverse().
reverse_lazy ( viewname , urlconf = None , args = None , kwargs = None , current_app = None )¶
Она полезна в тех случаях, когда необходимо использовать обратный URL до загрузки URLConf вашего проекта. Некоторые распространенные случаи, когда эта функция необходима:
- предоставление обратного URL в качестве атрибута url общего представления на основе класса.
- предоставление обратного URL декоратору (например, аргумент login_url для декоратора django.contrib.auth.decorators.permission_required() ).
- предоставление обратного URL в качестве значения по умолчанию для параметра в сигнатуре функции.
resolve() ¶
Функция resolve() может использоваться для преобразования URL-путей к соответствующим функциям представления. Она имеет следующую сигнатуру:
path — это путь URL, который вы хотите разрешить. Как и в случае с reverse() , вам не нужно беспокоиться о параметре urlconf . Функция возвращает объект ResolverMatch , который позволяет вам получить доступ к различным метаданным о разрешенном URL.
Если URL не разрешается, функция выдает исключение Resolver404 (подкласс Http404 ).
Функция представления, которая будет использоваться для обслуживания URL-адреса
Аргументы, которые будут переданы функции представления, как разобранные из URL.
Аргументы ключевых слов, которые будут переданы функции представления, как разобранные из URL.
Имя шаблона URL, который соответствует URL.
Маршрут, соответствующий шаблону URL.
Например, если path(‘users/<id>/’, . ) является совпадающим шаблоном, route будет содержать ‘users/<id>/’ .
Пространство имен приложения для шаблона URL, который соответствует URL.
Список отдельных компонентов пространства имен в полном пространстве имен приложения для шаблона URL, который соответствует URL. Например, если app_name будет ‘foo:bar’ , то app_names будет [‘foo’, ‘bar’] .
Пространство имен экземпляра для шаблона URL, который соответствует URL.
Список отдельных компонентов пространства имен в полном пространстве имен экземпляра для шаблона URL, который соответствует URL. т.е. если пространство имен foo:bar , то пространства имен будут [‘foo’, ‘bar’] .
Имя представления, которое соответствует URL, включая пространство имен, если оно есть.
Затем объект ResolverMatch может быть опрошен для получения информации о шаблоне URL, который соответствует URL:
Объект ResolverMatch также может быть присвоен тройке:
Одним из возможных вариантов использования resolve() может быть проверка того, будет ли представление выдавать ошибку Http404 перед перенаправлением на него:
get_script_prefix() ¶
Обычно для определения URL-адресов в вашем приложении всегда следует использовать reverse() . Однако, если ваше приложение само строит часть иерархии URL, вам иногда может понадобиться генерировать URL. В этом случае вам нужно иметь возможность найти базовый URL проекта Django внутри его Web-сервера (обычно reverse() заботится об этом за вас). В этом случае вы можете вызвать get_script_prefix() , который вернет префиксную часть URL вашего проекта Django. Если ваш проект Django находится в корне своего веб-сервера, то это всегда "/" .
Returning URLs
The central feature that distinguishes the REST architectural style from other network-based styles is its emphasis on a uniform interface between components.
— Roy Fielding, Architectural Styles and the Design of Network-based Software Architectures
As a rule, it’s probably better practice to return absolute URIs from your Web APIs, such as http://example.com/foobar , rather than returning relative URIs, such as /foobar .
The advantages of doing so are:
- It’s more explicit.
- It leaves less work for your API clients.
- There’s no ambiguity about the meaning of the string when it’s found in representations such as JSON that do not have a native URI type.
- It makes it easy to do things like markup HTML representations with hyperlinks.
REST framework provides two utility functions to make it more simple to return absolute URIs from your Web API.
There’s no requirement for you to use them, but if you do then the self-describing API will be able to automatically hyperlink its output for you, which makes browsing the API much easier.
reverse
Signature: reverse(viewname, *args, **kwargs)
Has the same behavior as django.urls.reverse , except that it returns a fully qualified URL, using the request to determine the host and port.
You should include the request as a keyword argument to the function, for example:
reverse_lazy
Signature: reverse_lazy(viewname, *args, **kwargs)
Has the same behavior as django.urls.reverse_lazy , except that it returns a fully qualified URL, using the request to determine the host and port.
As with the reverse function, you should include the request as a keyword argument to the function, for example:
django.urls utility functions¶
If you need to use something similar to the url template tag in your code, Django provides the following function:
reverse ( viewname , urlconf = None , args = None , kwargs = None , current_app = None )¶
viewname can be a URL pattern name or the callable view object. For example, given the following url :
you can use any of the following to reverse the URL:
If the URL accepts arguments, you may pass them in args . For example:
You can also pass kwargs instead of args . For example:
args and kwargs cannot be passed to reverse() at the same time.
If no match can be made, reverse() raises a NoReverseMatch exception.
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 namespaced URL resolution strategy .
The urlconf argument is the URLconf module containing the URL patterns to use for reversing. By default, the root URLconf for the current thread is used.
The string returned by reverse() is already urlquoted . For example:
Applying further encoding (such as urllib.parse.quote() ) to the output of reverse() may produce undesirable results.
reverse_lazy() ¶
A lazily evaluated version of reverse().
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 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 resolve() function can be used for resolving URL paths to the corresponding view functions. It has the following signature:
resolve ( path , urlconf = None )¶
path is the URL path you want to resolve. As with reverse() , you don’t need to worry about the urlconf parameter. The function returns a ResolverMatch object that allows you to access various metadata about the resolved URL.
If the URL does not resolve, the function raises a Resolver404 exception (a subclass of Http404 ) .
class ResolverMatch ¶ func ¶
The view function that would be used to serve the URL
The arguments that would be passed to the view function, as parsed from the URL.
All keyword arguments that would be passed to the view function, i.e. captured_kwargs and extra_kwargs .
The captured keyword arguments that would be passed to the view function, as parsed from the URL.
The additional keyword arguments that would be passed to the view function.
The name of the URL pattern that matches the URL.
The route of the matching URL pattern.
For example, if path(‘users/<id>/’, . ) is the matching pattern, route will contain ‘users/<id>/’ .
The list of URL patterns tried before the URL either matched one or exhausted available patterns.
The application namespace for the URL pattern that matches the URL.
The list of individual namespace components in the full application namespace for the URL pattern that matches the URL. For example, if the app_name is ‘foo:bar’ , then app_names will be [‘foo’, ‘bar’] .
The instance namespace for the URL pattern that matches the URL.
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’] .
The name of the view that matches the URL, including the namespace if there is one.
A ResolverMatch object can then be interrogated to provide information about the URL pattern that matches a URL:
A ResolverMatch object can also be assigned to a triple:
One possible use of resolve() would be to test whether a view would raise a Http404 error before redirecting to it:
get_script_prefix() ¶
Normally, you should always use reverse() 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, 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 "/" .
Additional Information
Support Django!
Contents
Browse
- Prev: Unicode data
- Next: django.urls functions for use in URLconfs
You are here:
- Django 4.1 documentation
- django.urls utility functions
- Hosting by In-kind donors
- Design by Threespot & andrevv
Getting help
Download:
Offline (Django 4.1): HTML | PDF | ePub
Provided by Read the Docs.Django Links
Learn More
Get Involved
Follow Us
Support Us
© 2005-2022 Django Software Foundation and individual contributors. Django is a registered trademark of the Django Software Foundation.