[Answered ]-Redirect and reverse differences in Django

1👍

The two are not the same for a number of reasons. The first one is that reverse(…) [Django-doc] returns a string that is a URL to visit that view. redirect(…) [Django-doc] on the other hand returns a HttpResponseRedirect object [Django-doc]. This object can be returned by the view, and will normally trigger the browser to visit the page specified in the HTTP response. redirect(…) has a special parameter permanent=… that will based on the value return a HttpResponseRedirect (if permanent=False which is the default), or HttpResponsePermanentRedirect for permanent=True.

Another difference is that the reverse(…) works with args=… and kwargs=… parameters to fill in the values for the URL patterns. This is different for redirect(…) where one passes the positional and named parameters just as positional and named parameters. This thus means that if you do a reverse('some_view', args=(some_parameter,), kwargs={'name': other_parameter}), you obtain a HTTP response that points to that URL with redirect('some_view', some_parameter, name=other_parameter).

A redirect(…) does not per se works on a view name. Indeed, if you pass a URL to the redirect(…) function, like redirect('/foo/bar/qux/'), it will construct a HttpResponseRedirect that redirects to the URL /foo/bar/qux. This is different for reverse(…) that only constructs URLs based on the name of the view, and its parameters.

Finally redirect(…) also accepts a model object that has a .get_absolute_url() method [Django-doc] will result in a HttpResponseRedirect that redirects to the URL constructed by that .get_absolute_url() method.

Your first (//1) and second (//2) line will thus produce the same result: a HttpResponseRedirect that redirects to the same URL, whereas the last one (//3) will return a string that contains a URL to the detail-page view.

0👍

According to https://docs.djangoproject.com/en/3.2/topics/http/shortcuts/#redirect 1 and 2 are equivalent. I would assume 3 doesn’t work as it’s missing the ?required? product id?

Leave a comment