How can I build multiple submit buttons django form?

Viewed 152497

I have form with one input for email and two submit buttons to subscribe and unsubscribe from newsletter:

<form action="" method="post">
{{ form_newsletter }}
<input type="submit" name="newsletter_sub" value="Subscribe" />
<input type="submit" name="newsletter_unsub" value="Unsubscribe" />
</form>

I have also class form:

class NewsletterForm(forms.ModelForm):
    class Meta:
        model = Newsletter
        fields = ('email',)

I must write my own clean_email method and I need to know by which button was form submited. But the value of submit buttons aren't in self.cleaned_data dictionary. Could I get values of buttons otherwise?

6 Answers

Eg:

if 'newsletter_sub' in request.POST:
    # do subscribe
elif 'newsletter_unsub' in request.POST:
    # do unsubscribe

You can use self.data in the clean_email method to access the POST data before validation. It should contain a key called newsletter_sub or newsletter_unsub depending on which button was pressed.

# in the context of a django.forms form

def clean(self):
    if 'newsletter_sub' in self.data:
        # do subscribe
    elif 'newsletter_unsub' in self.data:
        # do unsubscribe

I know this is old, but some of the answers are, to say the least, brief, and they do not address a common case where the form is not a django form.

This solution was inspired by this blog post. It relies on using a view class that is derived from django.views.generic.edit.FormMixin, e.g. CreateView, UpdateView or DeleteView. These provide the get_success_url method which exposes the button name in request

html

<html>
    <body>
        <form method="post">
            <div>
                <label> <input type="radio" name="select-type" value="A">Type A</label>
            </div>
            <div>
                <label> <input type="radio" name="select-type" value="B">Type B</label>
            </div>
            <div>
                <input type="submit" value="Use selected">
            </div>
            <div>
                <input type="submit" name="no-selection" value="None of the above">
            </div>
        </form>
    </body>
</html>

views.py

from django.views.generic import UpdateView

class GetType(UpdateView):
    def get(self, request):
        return render(request, 'get_type.html', {})

    def post(self, request):
        button = self.get_success_url()
        print(button)

    def get_success_url(self):
        if 'no-selection' in self.request.POST:
            return 'none selected'
        return ''
Related