Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two different submit buttons in same form in Django

I have an UpdateView in Django.

I have just a normal submit button. When the object is updated correctly it redirects to an object list via success_url.

Can I make two different submit buttons: One button which submits and redirects to objects list page (ListView) and another button which submits and redirects to the object detail page (DetailView)?

I don't know how to do this in a smart way.

like image 756
Jamgreen Avatar asked Oct 08 '14 12:10

Jamgreen


People also ask

Can I have two or more Submit buttons in the same form?

yes, multiple submit buttons can include in the html form. One simple example is given below.

Can you have multiple submit buttons in a form PHP?

Having multiple submit buttons and handling them through PHP is just a matter of checking the the name of the button with the corresponding value of the button using conditional statements. In this article I'll use both elseif ladder and switch case statement in PHP to handle multiple submit buttons in a form.


1 Answers

Since you're submitting to the same place, and only want to change the redirect destination after save, this is simple. Submit buttons are just like any other input controls in that they have a name and a value, and you receive these in the POST data. So, in your template you can have:

<input type="submit" name="list" value="Submit and go to list">
<input type="submit" name="detail" value="Submit and go to detail">

and in your view:

if form.is_valid():
    form.save()
    if 'list' in request.POST:
        return redirect('list_url')
    else:
        return redirect('detail_url')
like image 195
Daniel Roseman Avatar answered Sep 18 '22 15:09

Daniel Roseman