reverse django что это

Вспомогательные функции django.urls ¶

reverse() ¶

viewname может быть URL pattern name или вызываемым объектом представления. Например, учитывая следующее url :

вы можете использовать любой из следующих способов, чтобы изменить URL:

args и kwargs не могут быть переданы в reverse() одновременно.

Функция reverse() может отменить большое количество шаблонов регулярных выражений для URL, но не все возможные. Основным ограничением на данный момент является то, что шаблон не может содержать альтернативные варианты с использованием символа вертикальной черты ( «|» ). Вы вполне можете использовать такие шаблоны для сопоставления с входящими URL и отправки их в представления, но вы не можете обратить такие шаблоны.

Аргумент urlconf представляет собой модуль URLconf, содержащий шаблоны URL, которые следует использовать для реверсирования. По умолчанию используется корневой URLconf для текущего потока.

Применение дальнейшего кодирования (например, urllib.parse.quote() ) к выходу reverse() может привести к нежелательным результатам.

reverse_lazy() ¶

Лениво оцениваемая версия reverse().

Она полезна в тех случаях, когда необходимо использовать обратный URL до загрузки URLConf вашего проекта. Некоторые распространенные случаи, когда эта функция необходима:

resolve() ¶

Функция resolve() может использоваться для преобразования URL-путей к соответствующим функциям представления. Она имеет следующую сигнатуру:

Если URL не разрешается, функция выдает исключение Resolver404 (подкласс Http404 ).

class ResolverMatch [исходный код] ¶ func ¶

Функция представления, которая будет использоваться для обслуживания URL-адреса

Аргументы, которые будут переданы функции представления, как разобранные из URL.

Аргументы ключевых слов, которые будут переданы функции представления, как разобранные из URL.

Имя шаблона URL, который соответствует URL.

Маршрут, соответствующий шаблону URL.

Пространство имен приложения для шаблона URL, который соответствует URL.

Пространство имен экземпляра для шаблона URL, который соответствует URL.

Имя представления, которое соответствует URL, включая пространство имен, если оно есть.

Затем объект ResolverMatch может быть опрошен для получения информации о шаблоне URL, который соответствует URL:

Объект ResolverMatch также может быть присвоен тройке:

Одним из возможных вариантов использования resolve() может быть проверка того, будет ли представление выдавать ошибку Http404 перед перенаправлением на него:

get_script_prefix() ¶

Источник

Служебные функции django.urls ¶

reverse() ¶

Если вам нужно использовать что-то похожее на тег шаблона url в вашем коде, Django предоставляет следующую функцию:

viewname может быть именем шаблона URL или самим объектом представления. Например, учитывая url следующее:

вы можете использовать любой из следующих вызовов, чтобы получить URL:

Эта функция reverse() может разрешать широкий спектр шаблонов регулярных выражений, соответствующих URL-адресам, но не все. Основное ограничение в настоящее время заключается в том, что шаблон не может содержать различные возможные варианты, обозначенные вертикальной чертой ( «|» ). Такие шаблоны можно легко использовать для разрешения входящих URL-адресов и вызова соответствующего представления, но их нельзя использовать для выполнения обратных разрешений.

reverse_lazy() ¶

Эта функция полезна, когда вам нужно выполнить разрешение URL перед загрузкой конфигурации URL. Вот несколько распространенных случаев использования этой функции:

resolve() ¶

Функцию resolve() можно использовать для разрешения пути URL к соответствующей функции просмотра. Его подпись следующая:

Если URL-адрес не разрешен, функция генерирует исключение Resolver404 (которое является подклассом Http404 ).

класс ResolverMatch ¶ func ¶

Функция просмотра, которая использовалась бы для обслуживания URL.

Параметры, которые были бы переданы функции просмотра, поскольку они были взяты из URL-адреса.

Именованные параметры, которые были бы переданы функции просмотра, поскольку они были взяты из URL-адреса.

Имя шаблона URL-адреса, соответствующего URL-адресу.

Маршрут соответствующего шаблона URL.

Пространство имен приложения для шаблона URL, соответствующего URL.

Пространство имен экземпляра для шаблона URL, соответствующего URL.

Имя представления, соответствующего URL-адресу, включая пространство имен, если оно есть.

ResolverMatch Затем можно запросить объект, чтобы предоставить информацию о шаблоне URL, соответствующем URL:

Также объект ResolverMatch может быть отнесен к триплету:

Одним из возможных вариантов использования for resolve() может быть проверка того, выдает ли представление ошибку, Http404 прежде чем использовать его в качестве цели перенаправления:

get_script_prefix() ¶

Источник

Documentation

django.core.urlresolvers utility functions¶

reverse()¶

If you need to use something similar to the url template tag in your code, Django provides the following function:

you can use any of the following to reverse the URL:

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 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.

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.

Applying further encoding (such as urlquote() or urllib.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:

resolve()¶

The resolve() function can be used for resolving URL paths to the corresponding view functions. It has the following signature:

class ResolverMatch [source] ¶ 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.

The keyword arguments that would be passed to the view function, as parsed from the URL.

The name of the URL pattern that matches the URL.

The application namespace for the URL pattern that matches the URL.

The instance namespace for the URL pattern that matches the URL.

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()¶

Additional Information

Support Django!

reverse django что это. Смотреть фото reverse django что это. Смотреть картинку reverse django что это. Картинка про reverse django что это. Фото reverse django что это

Contents

Browse

You are here:

Getting help

Download:

Offline (Django 1.8): HTML | PDF | ePub
Provided by Read the Docs.

Источник

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 simple mapping between URL patterns (simple regular 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:

Named groups¶

The above example used simple, non-named regular-expression groups (via parenthesis) to capture bits of the URL and pass them as positional arguments to a view. In more advanced usage, it’s possible to use named regular-expression groups to capture URL bits and pass them as keyword arguments to a view.

Here’s the above example URLconf, rewritten to use named groups:

This accomplishes exactly the same thing as the previous example, with one subtle difference: The captured values are passed to view functions as keyword arguments rather than positional arguments. For example:

In practice, this means your URLconfs are slightly more explicit and less prone to argument-order bugs – and you can reorder the arguments in your views’ function definitions. Of course, these benefits come at the cost of brevity; some developers find the named-group syntax ugly and too verbose.

The matching/grouping algorithm¶

Here’s the algorithm the URLconf parser follows, with respect to named groups vs. non-named groups in a regular expression:

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¶

The URLconf searches against the requested URL, as a normal Python string. This does not include GET or POST parameters, or the domain name.

Captured arguments are always strings¶

Each captured argument is sent to the view as a plain Python string, regardless of what sort of match the regular expression makes. For example, in this URLconf line:

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 Python list of url() instances.

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 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 url() 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.

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.

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 django.conf.urls.url() 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() ¶

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.

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¶

Using this setup, the following lookups are possible:

In the method of a class-based view:

and in the template:

URL namespaces and included URLconfs¶

Application namespaces of included URLconfs can be specified in two ways.

Secondly, you can include an object that contains embedded namespace data. If you include() a list of url() instances, the URLs contained in that object will be added to the global namespace. However, you can also include() a 2-tuple containing:

This will include the nominated URL patterns into the given application namespace.

Источник

документация Django 3.0

reverse() ¶

viewname can be a URL pattern name or the callable view object. For example, given the following url :

вы можете получить URL одним из следующих способов:

Вы можете использовать kwargs (словарь) вместо args (отдельных аргументов). Например:

args и kwargs не могут быть переданы функции reverse() вместе, они используются по отдельности.

If no match can be made, reverse() raises a NoReverseMatch exception.

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.

Applying further encoding (such as urllib.parse.quote() ) to the output of reverse() may produce undesirable results.

reverse_lazy() ¶

lazy стоит расценивать как «ленивую» версию reverse().

Эта функция может быть полезна в случае, если вам нужно вернуть URL-адрес прежде, чем ваши настройки URLConf будут загружены. Перечислим несколько случаев, когда эта функция бывает необходима:

resolve() ¶

Функция resolve() может быть использована для получения URL-адреса из соответствующего представления. Она имеет следующий синтаксис:

class ResolverMatch ¶ func ¶

Функция представления, которая будет использована для передачи URL.

Аргументы, которые будут переданы в функцию представления, as parsed from the URL.

именованные аргументы, которые будут переданы в функцию представления, as parsed from the URL.

Название URL-шаблона для сопоставления URL-адресов.

The route of the matching URL pattern.

Название приложения из пространства имён для сопоставления URL-адресов.

Название выбранного пространства имён для сопоставления URL-адресов.

Название представления, которое обрабатывает URL, включая пространства имен, если таковы используются.

С помощью объекта ResolverMatch можно впоследствии запросить информацию о соответствии между URL-адресом и используемом имени представления (т.е. какому URL-адресу какой шаблон принадлежит):

Также объекту ResolverMatch можно передать три параметра:

One possible use of resolve() would be to test whether a view would raise a Http404 error before redirecting to it:

get_script_prefix() ¶

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *