-1

I need to redirect the user to a new page that says, "Thank you for contacting us" after submitting a form with Django.

I have tried using HttpResponseRedirect, reverse but I don't know how to implement it to all of the necessary files of my project.

from django.shortcuts import render
from .forms import ContactForm
# Create your views here.
def contact(request):
    template = "contact.html"

    if request.method == "POST":
        form = ContactForm(request.POST)

        if form.is_valid():
            form.save()

    else:
        form = ContactForm()

    context = {
        "form": form,
    }
    return render(request, template, context)

When I click submit, it sends the data to the Django database so the form does work but the user does not know that because after they click submit it doesn't redirect to a thank you page.

2 Answers2

1

Just build another view like the one you already have, with a new template and connect it to a new url. Then redirect the user to that url. Something like this:

in your urls.py:

from django.conf.urls import url
from .views import thank_you
urlpatterns = [
    url(r'^thanks/$', thank_you, name='thank-you'),
]

in your views.py:

from django.shortcuts import render

def thank_you(request):
    template = 'thank_you.html'
    context = {}
    return render(request, template, context)

in your contact view just return a redirect('/thanks/')

Matt
  • 324
  • 1
  • 8
0

For redirect to thanks page you can use this way

from django.shortcuts import render
from .forms import ContactForm
from django.core.urlresolvers import reverse
from django.http.response import HttpResponseRedirect

def contact(request):
   template = "contact.html"

   if request.method == "POST":
      form = ContactForm(request.POST)

      if form.is_valid():
         form.save()
         return HttpResponseRedirect(reverse("thanks_view_name"))

   else:
      form = ContactForm()

   context = {
      "form": form,
   }
   return render(request, template, context)

See example https://docs.djangoproject.com/en/2.1/topics/forms/#the-view

Andrey Leontyev
  • 421
  • 3
  • 11