简体   繁体   中英

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.

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM