Jason Howard
Jason Howard

Reputation: 1586

Muliple submit button on single form in Django

Within a form, I have two submit buttons. Depending on which button the user clicks on, I want the redirect on form.is_valid() to either be page A or page B. Do you know how I might be able to attach a different value to each submit button and pass this value on the POST request so that I can evaluate it in my view?

template.html

<div class="submitbutton"">
                <button type="submit">
                   Submit A
                </button>
            </div>

  <div class="submitbutton"">
                <button type="submit">
                   Submit B
                </button>
            </div>

views.py

 if request.method == 'POST':

    <!-- a bunch of code that works -->


   if user_clicked_SubmitA:     
         return redirect('profile')

   if user_clicked_SubmitB:
         return redirect('home')

THanks!

Upvotes: 0

Views: 71

Answers (2)

catavaran
catavaran

Reputation: 45575

Add the name attribute to your button :

<button type="submit" name="btn1" value="btn1">Button 1</button>
<button type="submit" name="btn2" value="btn2">Button 2</button>

and check for it in the view:

def my_view(request):
    if request.POST.get('btn1'):
        # first button clicked
    if request.POST.get('btn2'):
        # second

Update: added a value attributes to the <button> tags.

Upvotes: 2

Lavanya Pant
Lavanya Pant

Reputation: 702

You can do something as below

def my_view(request):
    post_data = request.POST
    if '_submit1' in post_data:
        return HttpResponseRedirect("")
    elif '_submit2' in post_data:
        return HttpResponseRedirect("")
    elif '_submit3' in post_data:
        return HttpResponseRedirect("")
    else:
        return HttpResponseRedirect("")



<form action="<view_url>">
<input type="submit" name="_submit1" />
<input type="submit" name="_submit2" />
<input type="submit" name="_submit3" />
</form>

Upvotes: 1

Related Questions