Django HttpResponseRedirect

David542 picture David542 · Apr 28, 2011 · Viewed 81.8k times · Source

I have created a basic contact form, and when the user submits information, it should redirect to the "Thank You" page.

views.py:

def contact(request):
    # if no errors...
    return HttpResponseRedirect('/thanks/')

urls.py:

(r'^contact/$', contact),
(r'^contact/thanks/$', contact_thanks),

Both pages work at the hard-coded URL. However, when I submit the form on /contact/ it redirects to /contact (no ending slash), which is a nonexistent page (either a 404 or an error page telling me I need a slash).

What is the reason it not correctly redirecting, and how can I fix this?

UPDATE: the return HttpResponseRedirect('/contact/thanks/') is what I now have, but the problem is that the submit button (using POST) does not redirect to the URL -- it doesn't redirect at all.

Answer

vad picture vad · Apr 29, 2011

It's not the POST button that should redirect, but the view.

If not differently specified, the form (the HTML form tag) POSTs to the same URL. If the form is on /contact/, it POSTs on /contact/ (with or without slash, it's the same).

It's in the view that you should redirect to thanks. From the doc:

def contact(request):
    if request.method == 'POST': # If the form has been submitted...
        form = ContactForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            # Process the data in form.cleaned_data
            # ...
            return HttpResponseRedirect('/thanks/') # Redirect after POST
    else:
        form = ContactForm() # An unbound form

    return render_to_response('contact.html', {
        'form': form,
    })

Change /thanks/ to /contact/thanks/ and you're done.