Что такое namespace в django
django.urls функции для использования в URLconfs¶
re_path() ¶
include() ¶
Обычно пространство имен приложения должно быть задано включенным модулем. Если пространство имен приложения задано, аргумент namespace может быть использован для задания другого пространства имен экземпляра.
include() также принимает в качестве аргумента либо итерабель, возвращающий шаблоны URL, либо кортеж, содержащий такую итерабель плюс имена пространств имен приложений.
register_converter() ¶
Функция для регистрации конвертера для использования в path() route s.
django.conf.urls функции для использования в URLconfs¶
static() ¶
Вспомогательная функция для возврата шаблона URL для обслуживания файлов в режиме отладки:
Не рекомендуется, начиная с версии 3.1: Псевдоним django.urls.re_path() для обратной совместимости.
handler400 ¶
Вызываемый объект, или строка, представляющая полный путь импорта Python к представлению, которое должно быть вызвано, если HTTP-клиент отправил запрос, вызвавший состояние ошибки и ответ с кодом состояния 400.
handler403 ¶
Вызываемый объект, или строка, представляющая полный путь импорта Python к представлению, которое должно быть вызвано, если у пользователя нет необходимых разрешений для доступа к ресурсу.
handler404 ¶
Вызываемый объект или строка, представляющая полный путь импорта Python к представлению, которое должно быть вызвано, если ни один из шаблонов URL не совпадает.
handler500 ¶
Вызываемый объект, или строка, представляющая полный путь импорта Python к представлению, которое должно быть вызвано в случае ошибок сервера. Ошибки сервера возникают, когда в коде представления есть ошибки времени выполнения.
Documentation
URL dispatcher¶
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.
See Cool URIs don’t change, by World Wide Web creator Tim Berners-Lee, for excellent arguments on why URLs should be clean and usable.
Overview¶
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).
This mapping can be as short or as long as needed. It can reference other mappings. And, because it’s pure Python code, it can be constructed dynamically.
Django also provides a way to translate URLs according to the active language. See the internationalization documentation for more information.
How Django processes a request¶
When a user requests a page from your Django-powered site, this is the algorithm the system follows to determine which Python code to execute:
Example¶
Here’s a sample URLconf:
Path converters¶
The following path converters are available by default:
Registering custom path converters¶
For more complex matching requirements, you can define your own path converters.
A converter is a class that includes the following:
Register custom converter classes in your URLconf using register_converter() :
Using regular expressions¶
Here’s the example URLconf from earlier, rewritten using regular expressions:
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.
Using unnamed regular expression groups¶
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.
Nested arguments¶
Regular expressions allow nested arguments, and Django will resolve them and pass them to the view. When reversing, Django will try to fill in all outer captured arguments, ignoring any nested captured arguments. Consider the following URL patterns which optionally take a page argument:
Nested captured arguments create a strong coupling between the view arguments and the URL as illustrated by blog_articles : the view receives part of the URL ( page-2/ ) instead of only the value the view is interested in. This coupling is even more pronounced when reversing, since to reverse the view we need to pass the piece of URL instead of the page number.
As a rule of thumb, only capture the values the view needs to work with and use non-capturing arguments when the regular expression needs an argument but the view ignores it.
What the URLconf searches against¶
The URLconf searches against the requested URL, as a normal Python string. This does not include GET or POST parameters, or the domain name.
Specifying defaults for view arguments¶
A convenient trick is to specify default parameters for your views’ arguments. Here’s an example URLconf and view:
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¶
urlpatterns should be a sequence of path() and/or re_path() instances.
Error handling¶
When Django can’t find a match for the requested URL, or when an exception is raised, Django invokes an error-handling view.
The views to use for these cases are specified by four variables. Their default values should suffice for most projects, but further customization is possible by overriding their default values.
See the documentation on customizing error views for the full details.
Such values can be set in your root URLconf. Setting these variables in any other URLconf will have no effect.
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.
Including other URLconfs¶
At any point, your urlpatterns can “include” other URLconf modules. This essentially “roots” a set of URLs below other ones.
For example, here’s an excerpt of the URLconf for the Django website itself. It includes a number of other URLconfs:
Another possibility is to include additional URL patterns by using a list of path() instances. For example, consider this URLconf:
In this example, the /credit/reports/ URL will be handled by the credit_views.report() Django view.
This can be used to remove redundancy from URLconfs where a single pattern prefix is used repeatedly. For example, consider this URLconf:
We can improve this by stating the common path prefix only once and grouping the suffixes that differ:
Captured parameters¶
An included URLconf receives any captured parameters from parent URLconfs, so the following example is valid:
In the above example, the captured «username» variable is passed to the included URLconf, as expected.
Passing extra options to view functions¶
URLconfs have a hook that lets you pass extra arguments to your view functions, as a Python dictionary.
The path() function can take an optional third argument which should be a dictionary of extra keyword arguments to pass to the view function.
This technique is used in the syndication framework to pass metadata and options to views.
Dealing with conflicts
It’s possible to have a URL pattern which captures named keyword arguments, and also passes arguments with the same names in its dictionary of extra arguments. When this happens, the arguments in the dictionary will be used instead of the arguments captured in the URL.
Passing extra options to include() ¶
Similarly, you can pass extra options to include() and each line in the included URLconf will be passed the extra options.
For example, these two URLconf sets are functionally identical:
Note that extra options will always be passed to every line in the included URLconf, regardless of whether the line’s view actually accepts those options as valid. For this reason, this technique is only useful if you’re certain that every view in the included URLconf accepts the extra options you’re passing.
Reverse resolution of URLs¶
A common need when working on a Django project is the possibility to obtain URLs in their final forms either for embedding in generated content (views and assets URLs, URLs shown to the user, etc.) or for handling of the navigation flow on the server side (redirections, etc.)
It is strongly desirable to avoid hard-coding these URLs (a laborious, non-scalable and error-prone strategy). Equally dangerous is devising ad-hoc mechanisms to generate URLs that are parallel to the design described by the URLconf, which can result in the production of URLs that become stale over time.
In other words, what’s needed is a DRY mechanism. Among other advantages it would allow evolution of the URL design without having to go over all the project source code to search and replace outdated URLs.
The primary piece of information we have available to get a URL is an identification (e.g. the name) of the view in charge of handling it. Other pieces of information that necessarily must participate in the lookup of the right URL are the types (positional, keyword) and values of the view arguments.
Django provides a solution such that the URL mapper is the only repository of the URL design. You feed it with your URLconf and then it can be used in both directions:
The first one is the usage we’ve been discussing in the previous sections. The second one is what is known as reverse resolution of URLs, reverse URL matching, reverse URL lookup, or simply URL reversing.
Django provides tools for performing URL reversing that match the different layers where URLs are needed:
Examples¶
Consider again this URLconf entry:
You can obtain these in template code by using:
If, for some reason, it was decided that the URLs where content for yearly article archives are published at should be changed then you would only need to change the entry in the URLconf.
In some scenarios where views are of a generic nature, a many-to-one relationship might exist between URLs and views. For these cases the view name isn’t a good enough identifier for it when comes the time of reversing URLs. Read the next section to know about the solution Django provides for this.
Naming URL patterns¶
In order to perform URL reversing, you’ll need to use named URL patterns as done in the examples above. The string used for the URL name can contain any characters you like. You are not restricted to valid Python names.
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 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. Path converters can also raise ValueError to indicate no match, see Registering custom path converters for details.
URL namespaces¶
Introduction¶
URL namespaces allow you to uniquely reverse named URL patterns even if different applications use the same URL names. It’s a good practice for third-party apps to always use namespaced URLs (as we did in the tutorial). Similarly, it also allows you to reverse URLs if multiple instances of an application are deployed. In other words, 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:
Reversing namespaced URLs¶
When given a namespaced URL (e.g. ‘polls:index’ ) to resolve, Django splits the fully qualified name into parts and then tries the following lookup:
First, Django looks for a matching application namespace (in this example, ‘polls’ ). This will yield a list of instances of that application.
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.
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’ ).
If there is no default application instance, Django will pick the last deployed instance of the application, whatever its instance name may be.
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¶
документация Django 3.0
Чистая, элегантная схема 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-сайта, используется такой алгоритм для определения какой код выполнить:
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.
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:
If the matched URL pattern contained no named groups, then the matches from the regular expression are provided as positional arguments.
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:
Path converters¶
The following path converters are available by default:
Registering custom path converters¶
For more complex matching requirements, you can define your own path converters.
A converter is a class that includes the following:
Register custom converter classes in your URLconf using register_converter() :
Using regular expressions¶
Here’s the example URLconf from earlier, rewritten using regular expressions:
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.
Using unnamed regular expression groups¶
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-ов, которые принимает необязательный номер страницы:
При получении URL-а для представления blog_articles необходимо указать самый внешний аргумент( page-2/ ) или ни одного аргумента в данном случае. В то время как для comments необходимо передать значение page_number или не одного аргумента.
Вложенные захватываемые аргументы создают сильную связанность между URL и аргументами представления, как это показано для blog_articles : представление получает часть URL-а ( page-2/ ) вместо значение, которое на самом деле необходимо представлению. Эта связанность особенно заметна при создании URL-а т.к. необходимо передать часть URL-а вместо номера страницы.
Как правило, URL-шаблон должен захватывать только необходимые для представления аргументы.
Что использует URLconf при поиске нужного шаблона URL¶
URLconf использует запрашиваемый URL как обычную строку Python. Он не учитывает параметры GET, POST и имя домена.
Значения по умолчанию для аргументов представления¶
Принято указывать значения по-умолчанию для аргументов представления. Пример URLconf и представления:
Производительность¶
Каждое регулярное выражение в urlpatterns будет скомпилировано при первом использовании. Это делает систему невероятно быстрой.
Syntax of the 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-шаблон.
Есть следующие переменные:
Комбинирование URLconfs¶
В любой момент, ваш urlpatterns может «включать» другие модули URLconf.
Вот пример URLconf для сайта Django. Он включает множество других конфигураций URL:
Another possibility is to include additional URL patterns by using a list of path() instances. For example, consider this URLconf:
Такой подход может применяться для уменьшения дублирования кода в настройках URL, когда используется один и тот же шаблонный префикс. Например, возьмём такую конфигурацию URL:
Мы можем сделать её проще, указав общий префикс только один раз и сгруппировав различающиеся суффиксы:
Нахождение аргументов в URL¶
Включенный URLconf получает все аргументы найденные родительским URLconfs, поэтому этот пример работает:
В примере выше, найденный аргумент «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.
Такой подход используется в 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 работают идентично:
Дополнительные аргументы всегда передаются каждому представлению во включенном URLconf, независимо от того, принимает оно эти аргументы или нет. Поэтому, такой подход полезен только если вы уверенны, что каждое представление принимает передаваемые аргументы.
Поиск URL-а по URL-шаблону¶
Обычной задачей является получение URL-а по его определению для отображения пользователю или для редиректа.
Очень важно не «хардкодить» URL-ы (трудоемкая и плохо поддерживаемая стратегия). Также не следует создавать «костыли» для генерации URL-ов, которые не следуют задокументированному дизайну URLconf.
В общем необходимо придерживаться принципа DRY. Немаловажно иметь возможность менять URL-ы в одном месте, а не выполнять поиск и замену по всему проекту.
Для получения URL-а нам необходим его идентификатор, то есть название URL-шаблона, и позиционные и именованные аргументы.
В Django для работы с URL-ами используется так называемый «URL mapper». Ему передается URLconf, и теперь его можно использовать в два направления:
Первое это то, что мы уже рассмотрели в предыдущем разделе. Второе называется URL reversing, в общем получение URL-а по его названию.
Django предоставляет инструменты для получения URL-ов в различных компонентах фреймворка:
Примеры¶
Рассмотрим следующий URLconf:
Вы можете получить его в шаблоне следующим образом:
Если по каким-либо причинам необходимо будет изменить URL, достаточно будет изменить запись в вашем URLconf.
В некоторых случаях URL-ы и представления могут соотноситься как многое-к-одному. В таких случаях название представления не может идентифицировать конкретный 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 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, если несколько экземпляров одного приложения подключены в конфигурацию URL-ов.
Пространство имен состоит из двух частей, каждая из которых это строка:
Поиск URL-а по шаблону с пространством имен¶
Если необходимо найти 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.
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-шаблонов определенных в приложении, найденном через пространство имен.