Чистая, элегантная схема URL-ов – это важная часть качественного приложения. Django позволяет проектировать URL-адреса как вы пожелаете, без ограничений «фреймворка».
Читайте Cool URIs don’t change, создателя World Wide Web, Тима Бернерса-Ли, чтобы узнать почему URL-ы должны быть красивыми и практичными.
To design URLs for an app, you create a Python module informally called a URLconf (URL configuration). This module is pure Python code and is a mapping between URL path expressions to Python functions (your views).
Эта конфигурация может быть короткой или длинной настолько, насколько это нужно. Она может ссылаться на другие конфигурации. И, так как это код Python, может создаваться динамически.
Django также предоставляет метод для перевода URL на текущий язык. Обратитесь к документации на интернационализацию для подробностей.
При запросе к странице вашего Django-сайта, используется такой алгоритм для определения какой код выполнить:
Django determines the root URLconf module to use. Ordinarily,
this is the value of the ROOT_URLCONF setting, but if the incoming
HttpRequest object has a urlconf
attribute (set by middleware), its value will be used in place of the
ROOT_URLCONF setting.
Django loads that Python module and looks for the variable
urlpatterns. This should be a sequence of
django.urls.path() and/or django.urls.re_path() instances.
Django runs through each URL pattern, in order, and stops at the first
one that matches the requested URL, matching against
path_info.
Once one of the URL patterns matches, Django imports and calls the given view, which is a Python function (or a class-based view). The view gets passed the following arguments:
Объект HttpRequest.
If the matched URL pattern contained no named groups, then the matches from the regular expression are provided as positional arguments.
The keyword arguments are made up of any named parts matched by the
path expression that are provided, overridden by any arguments specified
in the optional kwargs argument to django.urls.path() or
django.urls.re_path().
In older versions, the keyword arguments with None values are
made up also for not provided named parts.
If no URL pattern matches, or if an exception is raised during any point in this process, Django invokes an appropriate error-handling view. See Error handling below.
Вот пример простого URLconf:
from django.urls import path
from . import views
urlpatterns = [
path('articles/2003/', views.special_case_2003),
path('articles/<int:year>/', views.year_archive),
path('articles/<int:year>/<int:month>/', views.month_archive),
path('articles/<int:year>/<int:month>/<slug:slug>/', views.article_detail),
]
Заметим:
<int:name> to capture an integer parameter. If a converter isn’t included,
any string, excluding a / character, is matched.articles, not /articles.Примеры запросов:
/articles/2005/03/ would match the third entry in the
list. Django would call the function
views.month_archive(request, year=2005, month=3)./articles/2003/ соответствует первому выражению, не второму, потому что шаблоны проверяются по порядку и берется первый найденный. Не стесняйтесь использовать порядок для обработки различных ситуаций, таких как эта. В данном примере Django вызовет функцию views.special_case_2003(request)./articles/2003 не соответствует ни одному регулярному выражению, потому что каждое ожидает, что URL оканчивается на косую черту./articles/2003/03/building-a-django-site/ would match the final
pattern. Django would call the function
views.article_detail(request, year=2003, month=3, slug="building-a-django-site").The following path converters are available by default:
str - Matches any non-empty string, excluding the path separator, '/'.
This is the default if a converter isn’t included in the expression.int - Matches zero or any positive integer. Returns an int.slug - Matches any slug string consisting of ASCII letters or numbers,
plus the hyphen and underscore characters. For example,
building-your-1st-django-site.uuid - Matches a formatted UUID. To prevent multiple URLs from mapping to
the same page, dashes must be included and letters must be lowercase. For
example, 075194d3-6885-417e-a8a8-6c931e272f00. Returns a
UUID instance.path - Matches any non-empty string, including the path separator,
'/'. This allows you to match against a complete URL path rather than
a segment of a URL path as with str.For more complex matching requirements, you can define your own path converters.
A converter is a class that includes the following:
regex class attribute, as a string.to_python(self, value) method, which handles converting the matched
string into the type that should be passed to the view function. It should
raise ValueError if it can’t convert the given value. A ValueError is
interpreted as no match and as a consequence a 404 response is sent to the
user unless another URL pattern matches.to_url(self, value) method, which handles converting the Python type
into a string to be used in the URL.Например:
class FourDigitYearConverter:
regex = '[0-9]{4}'
def to_python(self, value):
return int(value)
def to_url(self, value):
return '%04d' % value
Register custom converter classes in your URLconf using
register_converter():
from django.urls import path, register_converter
from . import converters, views
register_converter(converters.FourDigitYearConverter, 'yyyy')
urlpatterns = [
path('articles/2003/', views.special_case_2003),
path('articles/<yyyy:year>/', views.year_archive),
...
]
If the paths and converters syntax isn’t sufficient for defining your URL
patterns, you can also use regular expressions. To do so, use
re_path() instead of path().
In Python regular expressions, the syntax for named regular expression groups
is (?P<name>pattern), where name is the name of the group and
pattern is some pattern to match.
Here’s the example URLconf from earlier, rewritten using regular expressions:
from django.urls import path, re_path
from . import views
urlpatterns = [
path('articles/2003/', views.special_case_2003),
re_path(r'^articles/(?P<year>[0-9]{4})/$', views.year_archive),
re_path(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$', views.month_archive),
re_path(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/(?P<slug>[\w-]+)/$', views.article_detail),
]
This accomplishes roughly the same thing as the previous example, except:
When switching from using path() to
re_path() or vice versa, it’s particularly important to be
aware that the type of the view arguments may change, and so you may need to
adapt your views.
As well as the named group syntax, e.g. (?P<year>[0-9]{4}), you can
also use the shorter unnamed group, e.g. ([0-9]{4}).
This usage isn’t particularly recommended as it makes it easier to accidentally introduce errors between the intended meaning of a match and the arguments of the view.
In either case, using only one style within a given regex is recommended. When both styles are mixed, any unnamed groups are ignored and only named groups are passed to the view function.
Регулярные выражения позволяют использовать вложенные аргументы, и Django может их найти и передать в представление. Во время поиска аргументов Django попытается получить самый внешний аргумент, игнорируя вложенные аргументы. Возьмем следующие шаблоны URL-ов, которые принимает необязательный номер страницы:
from django.urls import re_path
urlpatterns = [
re_path(r'^blog/(page-(\d+)/)?$', blog_articles), # bad
re_path(r'^comments/(?:page-(?P<page_number>\d+)/)?$', comments), # good
]
Оба шаблона используют вложенные аргументы и могут обрабатывать URL-ы: например, для blog/page-2/ будет найдено представление blog_articles с двумя позиционными аргументами page-2/ и 2. Второй URL-шаблон для comments для comments/page-2/ найдет именованный аргумент page_number со значеним 2. Внешний аргумент в этом случае не захватываемый из-за (?:...).
При получении URL-а для представления blog_articles необходимо указать самый внешний аргумент(page-2/) или ни одного аргумента в данном случае. В то время как для comments необходимо передать значение page_number или не одного аргумента.
Вложенные захватываемые аргументы создают сильную связанность между URL и аргументами представления, как это показано для blog_articles: представление получает часть URL-а (page-2/) вместо значение, которое на самом деле необходимо представлению. Эта связанность особенно заметна при создании URL-а т.к. необходимо передать часть URL-а вместо номера страницы.
Как правило, URL-шаблон должен захватывать только необходимые для представления аргументы.
URLconf использует запрашиваемый URL как обычную строку Python. Он не учитывает параметры GET, POST и имя домена.
Например, при запросе к https://www.example.com/myapp/, URLconf возьмет myapp/.
При запросе к https://www.example.com/myapp/?page=3 – myapp/.
URLconf не учитывает тип запроса. Другими словами, все типы запросов – POST, GET, HEAD, и др. – будут обработаны одним представлением при одинаковом URL.
Принято указывать значения по-умолчанию для аргументов представления. Пример URLconf и представления:
# URLconf
from django.urls import path
from . import views
urlpatterns = [
path('blog/', views.page),
path('blog/page<int:num>/', views.page),
]
# View (in blog/views.py)
def page(request, num=1):
# Output the appropriate page of blog entries, according to num.
...
In the above example, both URL patterns point to the same view –
views.page – but the first pattern doesn’t capture anything from the
URL. If the first pattern matches, the page() function will use its
default argument for num, 1. If the second pattern matches,
page() will use whatever num value was captured.
Каждое регулярное выражение в urlpatterns будет скомпилировано при первом использовании. Это делает систему невероятно быстрой.
urlpatterns variable¶urlpatterns should be a sequence of path()
and/or re_path() instances.
When Django can’t find a match for the requested URL, or when an exception is raised, Django invokes an error-handling view.
Эти представления определены в четырёх переменных. Их значения по-умолчанию должны подойти для большинства проектов, но вы можете их поменять при необходимости.
Подробности в разделе о переопределении обработчика ошибок.
Эти значения должны быть определены в главном URLconf.
Значение это функции, или полный путь для импорта, которая будет вызвана, если не был найден подходящий URL-шаблон.
Есть следующие переменные:
handler400 – Смотрите django.conf.urls.handler400.handler403 – Смотрите django.conf.urls.handler403.handler404 – Смотрите django.conf.urls.handler404.handler500 – Смотрите django.conf.urls.handler500.В любой момент, ваш urlpatterns может «включать» другие модули URLconf.
Вот пример URLconf для сайта Django. Он включает множество других конфигураций URL:
from django.urls import include, path
urlpatterns = [
# ... snip ...
path('community/', include('aggregator.urls')),
path('contact/', include('contact.urls')),
# ... snip ...
]
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.
Another possibility is to include additional URL patterns by using a list of
path() instances. For example, consider this URLconf:
from django.urls import include, path
from apps.main import views as main_views
from credit import views as credit_views
extra_patterns = [
path('reports/', credit_views.report),
path('reports/<int:id>/', credit_views.report),
path('charge/', credit_views.charge),
]
urlpatterns = [
path('', main_views.homepage),
path('help/', include('apps.help.urls')),
path('credit/', include(extra_patterns)),
]
В этом примере URL /credit/reports/ обработан представлением credit_views.report().
Такой подход может применяться для уменьшения дублирования кода в настройках URL, когда используется один и тот же шаблонный префикс. Например, возьмём такую конфигурацию URL:
from django.urls import path
from . import views
urlpatterns = [
path('<page_slug>-<page_id>/history/', views.history),
path('<page_slug>-<page_id>/edit/', views.edit),
path('<page_slug>-<page_id>/discuss/', views.discuss),
path('<page_slug>-<page_id>/permissions/', views.permissions),
]
Мы можем сделать её проще, указав общий префикс только один раз и сгруппировав различающиеся суффиксы:
from django.urls import include, path
from . import views
urlpatterns = [
path('<page_slug>-<page_id>/', include([
path('history/', views.history),
path('edit/', views.edit),
path('discuss/', views.discuss),
path('permissions/', views.permissions),
])),
]
Включенный URLconf получает все аргументы найденные родительским URLconfs, поэтому этот пример работает:
# In settings/urls/main.py
from django.urls import include, path
urlpatterns = [
path('<username>/blog/', include('foo.urls.blog')),
]
# In foo/urls/blog.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.blog.index),
path('archive/', views.blog.archive),
]
В примере выше, найденный аргумент "username" передается во включенный URLconf, как и ожидалось.
Конфигурация URL-ов позволяет определить дополнительные аргументы для функции представления, используя словарь Python.
The path() function can take an optional third argument
which should be a dictionary of extra keyword arguments to pass to the view
function.
Например:
from django.urls import path
from . import views
urlpatterns = [
path('blog/<int:year>/', views.year_archive, {'foo': 'bar'}),
]
In this example, for a request to /blog/2005/, Django will call
views.year_archive(request, year=2005, foo='bar').
Такой подход используется в syndication framework для передачи параметров и дополнительных данных в представление.
Конфликты переменных
Если регулярное выражение URL-шаблона выделяет из URL-а аргумент с названием, которое уже используется в дополнительных именованных аргументах, будет использован аргумент из словаря дополнительных аргументов, вместо значения из URL.
include()¶Similarly, you can pass extra options to include() and
each line in the included URLconf will be passed the extra options.
Например, эти два URLconf работают идентично:
Первый:
# main.py
from django.urls import include, path
urlpatterns = [
path('blog/', include('inner'), {'blog_id': 3}),
]
# inner.py
from django.urls import path
from mysite import views
urlpatterns = [
path('archive/', views.archive),
path('about/', views.about),
]
Второй:
# main.py
from django.urls import include, path
from mysite import views
urlpatterns = [
path('blog/', include('inner')),
]
# inner.py
from django.urls import path
urlpatterns = [
path('archive/', views.archive, {'blog_id': 3}),
path('about/', views.about, {'blog_id': 3}),
]
Дополнительные аргументы всегда передаются каждому представлению во включенном URLconf, независимо от того, принимает оно эти аргументы или нет. Поэтому, такой подход полезен только если вы уверенны, что каждое представление принимает передаваемые аргументы.
Обычной задачей является получение URL-а по его определению для отображения пользователю или для редиректа.
Очень важно не «хардкодить» URL-ы (трудоемкая и плохо поддерживаемая стратегия). Также не следует создавать «костыли» для генерации URL-ов, которые не следуют задокументированному дизайну URLconf.
В общем необходимо придерживаться принципа DRY. Немаловажно иметь возможность менять URL-ы в одном месте, а не выполнять поиск и замену по всему проекту.
Для получения URL-а нам необходим его идентификатор, то есть название URL-шаблона, и позиционные и именованные аргументы.
В Django для работы с URL-ами используется так называемый «URL mapper». Ему передается URLconf, и теперь его можно использовать в два направления:
Первое это то, что мы уже рассмотрели в предыдущем разделе. Второе называется URL reversing, в общем получение URL-а по его названию.
Django предоставляет инструменты для получения URL-ов в различных компонентах фреймворка:
url.reverse() function.get_absolute_url().Рассмотрим следующий URLconf:
from django.urls import path
from . import views
urlpatterns = [
#...
path('articles/<int:year>/', views.year_archive, name='news-year-archive'),
#...
]
According to this design, the URL for the archive corresponding to year nnnn
is /articles/<nnnn>/.
Вы можете получить его в шаблоне следующим образом:
<a href="{% url 'news-year-archive' 2012 %}">2012 Archive</a>
{# Or with the year in a template context variable: #}
<ul>
{% for yearvar in year_list %}
<li><a href="{% url 'news-year-archive' yearvar %}">{{ yearvar }} Archive</a></li>
{% endfor %}
</ul>
В Python коде:
from django.http import HttpResponseRedirect
from django.urls import reverse
def redirect_to_year(request):
# ...
year = 2006
# ...
return HttpResponseRedirect(reverse('news-year-archive', args=(year,)))
Если по каким-либо причинам необходимо будет изменить URL, достаточно будет изменить запись в вашем URLconf.
В некоторых случаях URL-ы и представления могут соотноситься как многое-к-одному. В таких случаях название представления не может идентифицировать конкретный URL. Как решить эту проблему читайте в следующем разделе.
Для того, чтобы выполнить обратное разрешение URL, вам потребуется использовать именованные URL шаблоны, как это показано в примерах выше. Строка, использованная для наименования URL, может содержать любые символы. Вы не ограничены только теми именами, что позволяет Python.
When naming URL patterns, choose names that are unlikely to clash with other
applications“ choice of names. If you call your URL pattern comment
and another application does the same thing, the URL that
reverse() finds depends on whichever pattern is last in
your project’s urlpatterns list.
Putting a prefix on your URL names, perhaps derived from the application
name (such as myapp-comment instead of comment), decreases the chance
of collision.
You can deliberately choose the same URL name as another application if you
want to override a view. For example, a common use case is to override the
LoginView. Parts of Django and most
third-party apps assume that this view has a URL pattern with the name
login. If you have a custom login view and give its URL the name login,
reverse() will find your custom view as long as it’s in
urlpatterns after django.contrib.auth.urls is included (if that’s
included at all).
You may also use the same name for multiple URL patterns if they differ in
their arguments. In addition to the URL name, reverse()
matches the number of arguments and the names of the keyword arguments.
Пространства имен позволяют получить URL по названию URL-шаблона даже, если несколько приложений используют одинаковые названия. Для сторонних приложений использование пространств имен – хорошая практика (как мы и делали в учебнике). Аналогично можно получить URL, если несколько экземпляров одного приложения подключены в конфигурацию URL-ов.
Django applications that make proper use of URL namespacing can be deployed
more than once for a particular site. For example django.contrib.admin
has an AdminSite class which allows you to
deploy more than one instance of the admin. In a
later example, we’ll discuss the idea of deploying the polls application from
the tutorial in two different locations so we can serve the same functionality
to two different audiences (authors and publishers).
Пространство имен состоит из двух частей, каждая из которых это строка:
admin.admin.Пространство имен определяется с помощью оператора ':'. Например, главная страница интерфейса администратора определяется как 'admin:index'. Мы видим пространство имен 'admin', и название URL-шаблона 'index'.
Пространства имен могут быть вложенными. Название URL-а 'sports:polls:index' означает именованный URL-шаблон с названием 'index' в пространстве имен 'polls', которое было определенно в другом пространстве имен - 'sports'.
Если необходимо найти URL по названию с пространством имен (например, 'polls:index'), Django разбивает название на части и следует такому алгоритму:
Первым делом, Django проверяет название(пространсву имен) приложения (например, polls). Django получает список экземпляров приложения.
If there is a current application defined, Django finds and returns the URL
resolver for that instance. The current application can be specified with
the current_app argument to the reverse()
function.
Шаблонный тег url использует пространство имен представления как текущее приложение в RequestContext. Вы можете переопределить его, указав в атрибуте request.current_app.
If there is no current application, Django looks for a default
application instance. The default application instance is the instance
that has an instance namespace matching the application
namespace (in this example, an instance of polls called 'polls').
Если экземпляр по-умолчанию не найден, Django возьмет последний установленный экземпляр приложения, не обращая внимание на его название.
Если на первом шаге не было найдено приложение по указанному пространству имен, Django попытается найти экземпляр приложения по его названию, используя пространство имен как название экземпляра.
Если пространство имен вложенное, этот процесс будет повторен, пока неопределенным не останется только название представления. URL для названия представления будет искаться среди URL-шаблонов определенных в приложении, найденном через пространство имен.
Разберем небольшой пример. У нас есть два экземпляра приложения polls: один назван 'author-polls', другой - 'publisher-polls'. Предположим, что мы уже изменили код приложения и оно учитывает текущее пространство имен при создании страниц.
from django.urls import include, path
urlpatterns = [
path('author-polls/', include('polls.urls', namespace='author-polls')),
path('publisher-polls/', include('polls.urls', namespace='publisher-polls')),
]
from django.urls import path
from . import views
app_name = 'polls'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('<int:pk>/', views.DetailView.as_view(), name='detail'),
...
]
Для таких настроек URL-ов возможны следующие варианты поиска URL-а по названию:
Если один из экземпляров указан как текущий - например, мы выполняем шаблон в экземпляре 'author-polls' - поиск URL-а по 'polls:index' вернет URL на главную страницу экземпляра приложения 'author-polls'. То есть мы получим "/author-polls/" для двух, приведенных ниже, примеров.
В методе представления:
reverse('polls:index', current_app=self.request.resolver_match.namespace)
и в шаблоне:
{% url 'polls:index' %}
Если текущий экземпляр приложения не указан - например, мы ищем URL в другом приложении - поиск по 'polls:index' вернет URL для последнего добавленного экземпляра 'polls'. Т.к. у нас не определен экземпляр приложения по умолчанию (с instance namespace равным 'polls'), будет использоваться последний добавленный экземпляр polls. Это будет 'publisher-polls' т.к. он последний в urlpatterns.
Поиск по 'author-polls:index' всегда вернет ссылку на главную страницу экземпляра приложения 'author-polls' (аналогично и для 'publisher-polls').
Если бы у нас был экземпляр приложения по умолчанию – то есть с instance name 'polls' – у нас бы поменялся результат только для тех случаев, где не указан текущий экземпляр (второй пункт в списке выше). В этом случае для 'polls:index' мы бы получили ссылку на главную страницу экземпляра приложения по умолчанию, а не для последнего в urlpatterns.
Название приложения в URLconfs можно определить двумя путями.
Firstly, you can set an app_name attribute in the included URLconf module,
at the same level as the urlpatterns attribute. You have to pass the actual
module, or a string reference to the module, to include(),
not the list of urlpatterns itself.
from django.urls import path
from . import views
app_name = 'polls'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('<int:pk>/', views.DetailView.as_view(), name='detail'),
...
]
from django.urls import include, path
urlpatterns = [
path('polls/', include('polls.urls')),
]
URL-ы, определенные в polls.urls, содержат название приложения polls.
Secondly, you can include an object that contains embedded namespace data. If
you include() a list of path() or
re_path() instances, the URLs contained in that object
will be added to the global namespace. However, you can also include() a
2-tuple containing:
(<list of path()/re_path() instances>, <application namespace>)
Например:
from django.urls import include, path
from . import views
polls_patterns = ([
path('', views.IndexView.as_view(), name='index'),
path('<int:pk>/', views.DetailView.as_view(), name='detail'),
], 'polls')
urlpatterns = [
path('polls/', include(polls_patterns)),
]
Этот код добавляет URL-шаблоны, используя указанное название приложения.
The instance namespace can be specified using the namespace argument to
include(). If the instance namespace is not specified,
it will default to the included URLconf’s application namespace. This means
it will also be the default instance for that namespace.
июн. 04, 2020