Reputation: 89
I create a form and I want then creating a button which acts as both "submit" and "href" at the same time. It means when I click on the button, it will submit the form and redirect to another page.
Current page: "http://127.0.0.1:8000/" Redirecting page after submitting: "http://127.0.0.1:8000/polls/"
I tried to add a link to action on form (code as below) but it doesn't work. It just redirects to the link without submitting any thing.
<form method='POST' action='http://127.0.0.1:8000/polls/' >{% csrf_token %}
<p>Questionnaire</P>
{{form.as_p}}
<input type="submit" value="Submit & Next Page"/>
</form>
My views.py:
from django.shortcuts import render
from .forms import SurveyForm
def homepage(request):
title = "Questionnaire"
form = SurveyForm(request.POST or None)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
context = {
"title": title,
"form": form,
}
return render(request, "homepage.html", context)
I would really appreciate if someone can help me. Thank you.
Upvotes: 2
Views: 1355
Reputation: 2901
You can do two methods (first is preferred):
First - In your views, you should have something like:
def view(request):
if request.method == 'POST':
form = SomeForm(request.POST)
if form.is_valid():
# Do something
# Add the line below to redirect to the name of a url
# after completion of the form
return HttpResponseRedirect(reverse('polls'))
Second - You can try adding onclick="window.location='http://127.0.0.1:8000/polls/'"
to your button. That should redirect it to the new window. For example:
<form method='POST' onclick="window.location='http://127.0.0.1:8000/polls/'">{% csrf_token %}
<p>Questionnaire</P>
{{form.as_p}}
<input type="submit" value="Submit & Next Page"/>
</form>
Note: If you choose the second method (probably shouldn't), it would be wise to use Django templating for the url (i.e. {% url 'polls' %} instead of http://127.0.0.1:8000/polls/)
Hope this helps!
Upvotes: 1
Reputation: 3729
The "normal" way is to POST the form to your view (This uses the action
link), and in this view function, you redirect to another URL when the form is all correct.
You normally have this code:
if request.method == "POST":
form = YourForm(request.POST)
if form.is_valid():
# do stuff
return HttpResponseRedirect(reverse(poll_url))
else:
form = YourForm(request.POST)
return render(request, <html file>, {'form': form})
Upvotes: 2
Reputation: 2347
You cannot perform two actions from one button/link. You have two solutions :
1\ Redirect :
Set your form to POST
on http://127.0.0.1/
. On the server side, you handle your form and send one http 301 response (Redirect).
2\ Send to /polls :
Keep everything like that on your form. But on server side, move your from handling to the same method that will render the page. So that, your method hnadle the form and then display the next page.
Upvotes: 1