How to build multiple submit buttons in a Python django form?

Estimated read time 2 min read

In Django, you can create a form with multiple submit buttons by using different names for each submit button and handling the form submission based on which button was clicked. Here’s an example:

from django import forms

class MyForm(forms.Form):
    name = forms.CharField(max_length=100)
    email = forms.EmailField()

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['submit_one'] = forms.Submit('Submit One', name='submit_one')
        self.fields['submit_two'] = forms.Submit('Submit Two', name='submit_two')

In this example, we define a MyForm class that inherits from Django’s forms.Form class. The form contains two fields for the user’s name and email, as well as two submit buttons named submit_one and submit_two. We add these submit buttons to the form by creating new Submit fields and setting their name attributes to the respective button names.

To handle the form submission, we can define a view function that checks which submit button was clicked by examining the request.POST dictionary. Here’s an example:

from django.shortcuts import render

def my_view(request):
    if request.method == 'POST':
        form = MyForm(request.POST)
        if form.is_valid():
            if 'submit_one' in request.POST:
                # Handle submission for Submit One button
            elif 'submit_two' in request.POST:
                # Handle submission for Submit Two button
        form = MyForm()
    return render(request, 'my_template.html', {'form': form})

In this example, we first check if the HTTP method of the request is POST. If so, we create a new instance of MyForm with the request data and validate it. We then check which submit button was clicked by examining the request.POST dictionary for the presence of either submit_one or submit_two. Depending on which button was clicked, we can perform different actions.

Finally, we pass the form instance to a template (my_template.html) and render it along with any context variables. In the template, we can access the two submit buttons using the form.submit_one and form.submit_two variables.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply