Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between HttpResponse vs HttpResponseRedirect vs render_to_response?

Tags:

The above-mentioned things give me almost the same results. I was wondering what is the main difference in them.

like image 921
Fahim Akhter Avatar asked Dec 17 '09 12:12

Fahim Akhter


People also ask

What is difference between HttpResponse and HttpResponseRedirect?

Chris Freeman. According to the docs, render Combines a given template with a given context dictionary and returns an HttpResponse object with that rendered text , while HttpResponseRedirect returns an HTTP status code 302 [redirect] along with the new URL.

What is difference between HttpResponse and render?

Abid covers it, render is usually used to load a template and a context, while HttpResponse is usually for data. As it's bad practice to "respond" with html. Render is essentially a shortuct for HttpResponse , It provides a more effective way to modify templates, and load data dynamically.

What is HttpResponseRedirect?

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.


1 Answers

  1. response = HttpResponse("Here's the text of the Web page."):
    will create a new HttpResponse object with HTTP code 200 (OK), and the content passed to the constructor. In general, you should only use this for really small responses (like an AJAX form return value, if its really simple - just a number or so).

  2. HttpResponseRedirect("http://example.com/"):
    will create a new HttpResponse object with HTTP code 302 (Found/Moved temporarily). This should be used only to redirect to another page (e.g. after successful form POST)

From the docs:

class HttpResponseRedirect The constructor takes a single argument -- the path to redirect to. This can be a fully qualified URL (e.g. 'http://www.yahoo.com/search/') or an absolute URL with no domain (e.g. '/search/'). Note that this returns an HTTP status code 302.

enough said...

render_to_response(template[, dictionary][, context_instance][,mimetype])
Renders a given template with a given context dictionary and returns an HttpResponse object with that rendered text.

is a call to render a template with given dictionary of variables to create the response for you. This is what you should be using most of the time, because you want to keep your presentation logic in templates and not in code.

like image 116
Ofri Raviv Avatar answered Sep 21 '22 08:09

Ofri Raviv