Having multiple submit buttons in a Django form can be very useful for accomplishing different actions with the same set of data. For example, you may want a “Save Draft” button in addition to a “Publish” button for blog posts or other content.
In this blog post, we will walk through a simple technique to create multiple submit buttons in a Django form.
Prerequisites
Before getting started, let’s outline some prerequisites:
- Basic knowledge of Python, HTML, and Django framework
- Django project set up on your machine
- Familiarity with Django forms
With those basics covered, you’re ready to follow along and add multiple submit buttons to your Django project.
Creating the Form
First, we need to build out a basic Django form. This will contain the fields to collect data from users:
from django import forms
class ExampleForm(forms.Form):
title = forms.CharField()
content = forms.CharField(widget=forms.Textarea)
This simple form has just two fields – a title and some content text.
Adding Submit Buttons in Form
Next, open the template where you want the form to be rendered. This is where we can add multiple submit buttons.
First, render theForm using simple Django template tags:
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
</form>
Now we can add ourSubmit buttons. Do this by creating input fields manually, outside of theForm rendering:
<input type="submit" name="save_draft" value="Save as Draft">
<input type="submit" name="publish" value="Publish">
Notice that we are giving each button a distinct name value. This is crucial for distinguishing between the different submissions.
Handling Submissions
The last step is to update the view logic to handle the different submit actions.
Start by checking the POST data:
if request.method == "POST":
button_name = request.POST.get('save_draft') or request.POST.get('publish')
Then take appropriate action depending on which was clicked:
if button_name == 'save_draft':
// Save form data as draft
if button_name == 'publish':
// Publish form data
And that’s it! The multiple submit buttons will now properly execute their corresponding actions.
Summary
Create a Django form in the conventional manner, adhering to standard practices. Next, manually integrate submit buttons into the corresponding template, ensuring each button is assigned a distinct name value. Subsequently, during the handling of POST data, scrutinize which button was clicked. Following this assessment, implement custom logic based on the identity of the clicked submit button.
The benefit of this technique is it avoids the need for any JavaScript or other complex logic. The buttons smoothly integrate with the standard Django form handling.
So there you have it – an easy way to add multiple submit actions to any Django form!