Reputation: 776
Is it possible to redirect to a page or another when sending a request.POST in a Django view, depending on which button has been used?
Example:
<form id="myForm" action='?'>
<submit button1>
<submit button2>
</form>
and then in my view:
if request.method == "POST":
if form.is_valid() and button1:
form.save()
return redirect('page1')
if form.is_valid() and button2:
form.save()
return redirect('page2')
Upvotes: 2
Views: 740
Reputation: 2613
You may try this:
html
<form>
<input type="submit" name="button1">
<input type="submit" name="button2">
</form>
Views.py
if request.method == "POST":
if form.is_valid() and 'button1' in request.POST:
form.save()
return redirect('page1')
if form.is_valid() and 'button2' in request.POST:
form.save()
return redirect('page2')
Upvotes: 1
Reputation: 793
Yes. Give your submit buttons the same name but different values
<button type="submit" name="submit" value="button1">Button 1</button>
<button type="submit" name="submit" value="button2">Button 2</button>
Which button was clicked will then be available in request.POST
if request.method == "POST" and form.is_valid():
form.save()
if request.POST['submit'] == 'button1':
return redirect('page1')
elif request.POST['submit'] == 'button2':
return redirect('page2')
Upvotes: 1
Reputation: 776
I've solved it like so:
<input class="button" value='update' type="submit" name="action" form="eventForm"/>
<input class="button" value='submit' type="submit" name="action" form="eventForm"/>
And then in the view:
if request.POST['action'] == 'submit':
[...]
elif request.POST['action'] == 'update'
Upvotes: 1