Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What the difference between using Django redirect and HttpResponseRedirect?

Which is it better to use generally?

  • https://docs.djangoproject.com/en/dev/topics/http/shortcuts/#redirect

  • https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpResponseRedirect

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?

like image 354
Williams Avatar asked Nov 09 '12 07:11

Williams


People also ask

What does HttpResponseRedirect do in Django?

HttpResponseRedirect is a subclass of HttpResponse (source code) in the Django web framework that returns the HTTP 302 status code, indicating the URL resource was found but temporarily moved to a different URL. This class is most frequently used as a return object from a Django view.

Can we send data with redirect in Django?

You can now perform a redirect with Django, either by using the redirect response classes HttpResponseRedirect and HttpResponsePermanentRedirect , or with the convenience function django. shortcuts. redirect() .

Which Django function returns an HttpResponseRedirect to the appropriate URL for the arguments passed?

redirect() Returns an HttpResponseRedirect to the appropriate URL for the arguments passed. The arguments could be: A model: the model's get_absolute_url() function will be called. A view name, possibly with arguments: reverse() will be used to reverse-resolve the name.

How do I move one page to a different page in Django?

In Django, redirection is accomplished using the 'redirect' method. The 'redirect' method takes as argument: The URL you want to be redirected to as string A view's name. In the above example, first we imported redirect from django.


1 Answers

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.

like image 139
Marwan Alsabbagh Avatar answered Oct 20 '22 00:10

Marwan Alsabbagh