Reverse django что это

от admin

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:

Зачем нужен reverse()?

reverse позволяет по имени вьюхи получить её url.

get_absolute_url — позволяет получить канонический URL обьекта, при условии что этот метод определён.

  • Facebook
  • Вконтакте
  • Twitter

stympel

deepblack

Не очень. Обычно импорты пишут в начале файла.

Но если кроме этой функции импортируемое нигде не используется,
то иногда делают импорт из функции.

Django Reverse URL – reverse() function

Managing URLs in Django can become very cumbersome if you don’t employ the right tactic in the beginning. Imagine that you have to deal with thousands of hardcoded URLs and know which one to use for each situation. To make it easier, the Django reverse() function can be used.

In short, the Django reverse function is used to transform a view name given to the URL pattern into an actual URL. A quick example of usage is shown below.

Django reverse() function explained

When resolving incoming requests, Django tries to match the URL pattern (URL -> view name) , then picks the right view and generates a response.

But when you need to go another way around, you’ll want to pick a view and build an appropriate URL out of it (view name -> URL) . For that purpose, you can use the django.urls.reverse function. The main point of using this function is to avoid hardcoding URLs which keeps you from breaking your application if you decide to change URL paths in the future.

The reverse() function is commonly used in pair with the redirect logic. You can learn more about redirects in our Django Redirect Explained post.

Let’s see what the function constructor looks like.

reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None)

  • viewname – name of the view (URL pattern name) or the callable view object for which the URL will be generated.
  • urlconf – URLconf module containing the URL patterns to use for reversing.
  • args – arguments if URL accepts them.
  • kwargs – keyword-arguments if URL accepts them.
  • current_app – application to which the currently executing view belongs.

Examples of Django reverse() function usage

In this section, we’ll show how to use the reverse() function:

  • without additional arguments and parameters,
  • with args,
  • with kwargs

Using Django reverse() function without additional arguments

To make it clear what our URL patterns look like, let’s take a sneak peek into urls.py.

Now if we want to use the original-url/ to redirect the request to the another-url/ we can define the logic inside the original_view (in the views.py). Here we pass the named-url string to the reverse() function to point to the correct view.

Another way of correct usage is by passing the callable view object as the first argument. In the example below, we are passing the another_view as a function argument.

Using reverse() function with args

Sometimes you’ll have a URL pattern that expects an additional parameter. You can notice in the urls.py that the another-url/ has an additional parameter defined, which allows it to look like any of the following URL paths: another-url/dummy/ , another-url/123/ , etc.

To reverse the view into a URL, inside the views.py we need to somehow tell the Django that the URL expects an additional argument. We do that by passing the args list as an additional argument to the reverse() function constructor. Doing this will reverse with arguments, constructing a full URL path.

Читать:
Как добавить приложение в трей

Using reverse() function with kwargs

Similarly, sometimes you’ll need to construct a URL that expects additional key-value parameters. In the urls.py you can see what such a URL pattern looks like.

To reverse with additional kwargs arguments, we need to pass the kwargs object as an additional argument to the reverse() function constructor. Doing this will construct a full URL path taking into consideration a kwargs object.

Django reverse_lazy() function

If you need a URL reversal before your project’s URLconf is loaded, you can use the django.urls.reverse_lazy function. It is a lazily evaluated version of reverse() .

This function is commonly used in generic class-based views. Take a look at the following example.

As you can see, we presented two ways of defining a success URL. The first one is by using the success_url attribute directly inside the CreateItemView class. This attribute will be evaluated exactly at the moment the class itself is imported; therefore we must use the lazily evaluated version.

On the other hand, if we build the success URL by using the get_success_url function, then we can use the reverse() function because it will be evaluated exactly when it’s called.

Ezoic

report this ad

What is reverse()?

When I read Django code sometimes, I see in some templates reverse() . I am not quite sure what this is but it is used together with HttpResponseRedirect. How and when is this reverse() supposed to be used?

7 Answers 7

Let’s suppose that in your urls.py you have defined this:

In a template you can then refer to this url as:

This will be rendered as:

Now say you want to do something similar in your views.py — e.g. you are handling some other URL (not /foo/ ) in some other view (not some_view ) and you want to redirect the user to /foo/ (often the case on successful form submission).

You could just do:

But what if you want to change the URL in the future? You’d have to update your urls.py and all references to it in your code. This violates the DRY (Don’t Repeat Yourself) principle and the whole idea of editing in one place only — which is something to strive for.

Instead, you can say:

This looks through all URLs defined in your project for the URL defined with the name url_name and returns the actual URL /foo/ .

This means that you refer to the URL only by its name attribute — if you want to change the URL itself or the view it refers to you can do this by editing one place only — urls.py .

Tiago Martins Peres's user avatar

The existing answers are quite clear. Just in case you do not know why it is called reverse : It takes an input of a url name and gives the actual url, which is reverse to having a url first and then give it a name.

Existing answers did a great job at explaining the what of this reverse() function in Django.

However, I’d hoped that my answer shed a different light at the why: why use reverse() in place of other more straightforward, arguably more pythonic approaches in template-view binding, and what are some legitimate reasons for the popularity of this «redirect via reverse() pattern» in Django routing logic.

One key benefit is the reverse construction of a url, as others have mentioned. Just like how you would use <% url "profile" profile.id %>to generate the url from your app’s url configuration file: e.g. path(‘<int:profile.id>/profile’, views.profile, name=»profile») .

But as the OP have noted, the use of reverse() is also commonly combined with the use of HttpResponseRedirect . But why?

I am not quite sure what this is but it is used together with HttpResponseRedirect. How and when is this reverse() supposed to be used?

Consider the following views.py :

And our minimal urls.py :

In the vote() function, the code in our else block uses reverse along with HttpResponseRedirect in the following pattern:

This first and foremost, means we don’t have to hardcode the URL (consistent with the DRY principle) but more crucially, reverse() provides an elegant way to construct URL strings by handling values unpacked from the arguments ( args=(question.id) is handled by URLConfig). Supposed question has an attribute id which contains the value 5 , the URL constructed from the reverse() would then be:

In normal template-view binding code, we use HttpResponse() or render() as they typically involve less abstraction: one view function returning one template:

But in many legitimate cases of redirection, we typically care about constructing the URL from a list of parameters. These include cases such as:

  • HTML form submission through POST request
  • User login post-validation
  • Reset password through JSON web tokens

Most of these involve some form of redirection, and a URL constructed through a set of parameters. Hope this adds to the already helpful thread of answers!

Похожие статьи