Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use HttpResponseRedirect here?

Tags:

python

django

I am doing the Tango with Django tutorial and I have completed the tutorials successfully however I noticed in the official Django Polls tutorial, the following:

def vote(request, question_id):
p = get_object_or_404(Question, pk=question_id)
try:
    selected_choice = p.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
    # Redisplay the question voting form.
    return render(request, 'polls/detail.html', {
        'question': p,
        'error_message': "You didn't select a choice.",
    })
else:
    selected_choice.votes += 1
    selected_choice.save()
    # Always return an HttpResponseRedirect after successfully dealing
    # with POST data. This prevents data from being posted twice if a
    # user hits the Back button.
    return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))

The part to notice here is the "Always return an HttpResponseRedirect after successfully dealing with POST data." However, in the Tango with Django tutorial:

def add_page(request, category_name_url):
context = RequestContext(request)

category_name = decode_url(category_name_url)

if request.method == 'POST':
    form = PageForm(request.POST)

    if form.is_valid():
        page = form.save(commit=False)

        try:
            cat = Category.objects.get(name=category_name)
            page.category = cat
        except Category.DoesNotExist:
            return render_to_response('rango/add_category.html', {}, context)

        page.views = 0
        page.save()

        return category(request, category_name_url)
    else:
        print(form.errors)
else:
    form = PageForm()

return render_to_response('rango/add_page.html',
                         {'category_name_url': category_name_url,
                          'category_name'    : category_name,
                          'form'             : form}, context)

Notice the lack of HttpResponseRedirect despite the use of POST data. I don't know if this is correct or not?

I have looked here: Django HttpResponseRedirect

Here: Django: HttpResponseRedirect not working

And here: Django HttpResponseRedirect vs render_to_response - how to get a login form to behave the way I need it to

Also, here: Django form redirect using HttpResponseRedirect

And finally here: Django: What is the difference b/w HttpResponse vs HttpResponseRedirect vs render_to_response

I still do not understand fully how to use HttpResponseRedirect. Please, help.

Thanks in advance to anyone who responds.

like image 773
Josh Wiegand Avatar asked Mar 04 '14 00:03

Josh Wiegand


People also ask

What is the use of 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.

What is the difference between redirect and HttpResponseRedirect?

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.

When to use redirect in Django?

You might want to redirect a user to another page when a specific action occurs, or basically in case of error. For example, when a user logs in to your website, he is often redirected either to the main home page or to his personal dashboard. In Django, redirection is accomplished using the 'redirect' method.

How to redirect to another URL in Django views?

As already suggested by @mdegis you can use the Django redirect function to redirect to another view or url. You can pass positional or keyword argument(s) to the redirect shortcut using the reverse() method and the named url of the view you're redirecting to.

What is the difference between render and httpresponseredirect?

Thanks! 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. So render sends back a typical web page, while HttpResponseRedirect sends back a URL.

What is httpresponseredirect in Django?

Django HttpResponseRedirect is a subclass of HttpResponse that redirects the user to a specific URL. In this tutorial, we'll cover Django HttpResponseRedirect, so pay attention and let's get started.

Should I use render_to_response after processing posts?

render_to_response should not be used after processing POSTs. After POST processing a redirect is a better choice because it won't display the message saying the form will be resubmitted. I actually wrote that in my answer...


1 Answers

This is common practice to prevent the user resubmitting the form after the initial POST request has been processed server side.

If you don't use HttpResponseRedirect after processing a POST request, the consequences might be that you inadvertently insert multiple duplicate rows into your database or send a confirmation email more than once etc.

like image 199
dannymilsom Avatar answered Oct 22 '22 13:10

dannymilsom