What the difference between using Django redirect and HttpResponseRedirect?

PythonDjangoRedirect

Python Problem Overview


Which is it better to use generally?

Is there any advantage to writing:

return redirect(my_url)

over:

return HttpResponseRedirect(my_url)

Or is it a direct alias? Is there any difference? Which is more pythonic/django-nic?

Python Solutions


Solution 1 - Python

There is a difference between the two:

In the case of HttpResponseRedirect the first argument can only be a url.

redirect which will ultimately return a HttpResponseRedirect can accept a model, view, or url as it's "to" argument. So it is a little more flexible in what it can "redirect" to.

I also like how redirect is shorter. So I'd use redirect over HttpResponseRedirect.

Both are fine to use though.

Solution 2 - Python

From documentation -

> redirect(to[, permanent=False], *args, **kwargs) Returns an > HttpResponseRedirect to the appropriate URL for the arguments passed.

from the definition its the same. Thats what shortcuts are for. Both are one and the same.

shortcuts generally are written one level above the actual API's. So redirect encapsulates HttpResponseRedirect and HttpResponsePermanentRedirect with the arg permanent=False.

There is no major downside to using HttpResponseRedirect over redirect. Hope this clears it.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWilliamsView Question on Stackoverflow
Solution 1 - PythonMarwan AlsabbaghView Answer on Stackoverflow
Solution 2 - PythonSrikar AppalarajuView Answer on Stackoverflow