django.urls utility functions¶reverse()¶Если вам нужно вернуть абсолютную ссылку, соответствующую указанному представлению, как это делает url, Django предоставляет следующую функцию:
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:
from news import views
path('archive/', views.archive, name='news-archive')
вы можете получить URL одним из следующих способов:
# using the named URL
reverse('news-archive')
# passing a callable object
# (This is discouraged because you can't reverse namespaced views this way.)
from news import views
reverse(views.archive)
Если URL принимает аргументы, вы можете их передать аргументом args. Например:
from django.urls import reverse
def myview(request):
return HttpResponseRedirect(reverse('arch-summary', args=[1945]))
Вы можете использовать kwargs (словарь) вместо args (отдельных аргументов). Например:
>>> reverse('admin:app_list', kwargs={'app_label': 'auth'})
'/admin/auth/'
args и kwargs не могут быть переданы функции reverse() вместе, они используются по отдельности.
If no match can be made, reverse() raises a
NoReverseMatch exception.
Функция reverse() может предоставлять достаточно большое количество шаблонов регулярных выражений, но не все из возможных. На данный момент шаблон не предоставляет возможности использования символа вертикальной черты ("|") для указания альтернативного выбора. Вы можете использовать такой шаблон для обработки входящего URL-а и получения представления, но вы не можете получить URL для такого шаблона с помощью reverse().
Аргумент current_app позволит вам получить полный путь к текущей странице. Он возвращает текущий экземпляр приложения из указанного пространства имён.
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.
Примечание
Строка, которую возвращает reverse(), уже кодирована. Чтобы узнать об этом подробнее смотрите urlquoted. Пример:
>>> reverse('cities', args=['Orléans'])
'.../Orl%C3%A9ans/'
Applying further encoding (such as urllib.parse.quote()) to the output
of reverse() may produce undesirable results.
reverse_lazy()¶lazy стоит расценивать как «ленивую» версию reverse().
reverse_lazy(viewname, urlconf=None, args=None, kwargs=None, current_app=None)¶Эта функция может быть полезна в случае, если вам нужно вернуть URL-адрес прежде, чем ваши настройки URLConf будут загружены. Перечислим несколько случаев, когда эта функция бывает необходима:
url атрибута для представления базовых классов.login_url для django.contrib.auth.decorators.permission_required()).resolve()¶Функция resolve() может быть использована для получения URL-адреса из соответствующего представления. Она имеет следующий синтаксис:
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) .
ResolverMatch¶func¶Функция представления, которая будет использована для передачи URL.
args¶Аргументы, которые будут переданы в функцию представления, as parsed from the URL.
kwargs¶именованные аргументы, которые будут переданы в функцию представления, as parsed from the URL.
url_name¶Название URL-шаблона для сопоставления URL-адресов.
route¶The route of the matching URL pattern.
For example, if path('users/<id>/', ...) is the matching pattern,
route will contain 'users/<id>/'.
app_name¶Название приложения из пространства имён для сопоставления URL-адресов.
app_names¶Список пространств имен, из которых состоит полное пространство имен приложения для URL-шаблона, который удовлетворяет URL-у. Для foo:bar это будет ['foo', 'bar'].
namespace¶Название выбранного пространства имён для сопоставления URL-адресов.
namespaces¶Список пространств имен. Для foo:bar это будет ['foo', 'bar'].
view_name¶Название представления, которое обрабатывает URL, включая пространства имен, если таковы используются.
С помощью объекта ResolverMatch можно впоследствии запросить информацию о соответствии между URL-адресом и используемом имени представления (т.е. какому URL-адресу какой шаблон принадлежит):
# Resolve a URL
match = resolve('/some/path/')
# Print the URL pattern that matches the URL
print(match.url_name)
Также объекту ResolverMatch можно передать три параметра:
func, args, kwargs = resolve('/some/path/')
One possible use of resolve() would be to test whether a
view would raise a Http404 error before redirecting to it:
from urllib.parse import urlparse
from django.urls import resolve
from django.http import Http404, HttpResponseRedirect
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
get_script_prefix()¶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 "/".
июн. 04, 2020