Proper way to handle multiple forms on one page in Django Proper way to handle multiple forms on one page in Django python python

Proper way to handle multiple forms on one page in Django


You have a few options:

  1. Put different URLs in the action for the two forms. Then you'll have two different view functions to deal with the two different forms.

  2. Read the submit button values from the POST data. You can tell which submit button was clicked: How can I build multiple submit buttons django form?


A method for future reference is something like this. bannedphraseform is the first form and expectedphraseform is the second. If the first one is hit, the second one is skipped (which is a reasonable assumption in this case):

if request.method == 'POST':    bannedphraseform = BannedPhraseForm(request.POST, prefix='banned')    if bannedphraseform.is_valid():        bannedphraseform.save()else:    bannedphraseform = BannedPhraseForm(prefix='banned')if request.method == 'POST' and not bannedphraseform.is_valid():    expectedphraseform = ExpectedPhraseForm(request.POST, prefix='expected')    bannedphraseform = BannedPhraseForm(prefix='banned')    if expectedphraseform.is_valid():        expectedphraseform.save()else:    expectedphraseform = ExpectedPhraseForm(prefix='expected')


I needed multiple forms that are independently validated on the same page. The key concepts I was missing were 1) using the form prefix for the submit button name and 2) an unbounded form does not trigger validation. If it helps anyone else, here is my simplified example of two forms AForm and BForm using TemplateView based on the answers by @adam-nelson and @daniel-sokolowski and comment by @zeraien (https://stackoverflow.com/a/17303480/2680349):

# views.pydef _get_form(request, formcls, prefix):    data = request.POST if prefix in request.POST else None    return formcls(data, prefix=prefix)class MyView(TemplateView):    template_name = 'mytemplate.html'    def get(self, request, *args, **kwargs):        return self.render_to_response({'aform': AForm(prefix='aform_pre'), 'bform': BForm(prefix='bform_pre')})    def post(self, request, *args, **kwargs):        aform = _get_form(request, AForm, 'aform_pre')        bform = _get_form(request, BForm, 'bform_pre')        if aform.is_bound and aform.is_valid():            # Process aform and render response        elif bform.is_bound and bform.is_valid():            # Process bform and render response        return self.render_to_response({'aform': aform, 'bform': bform})# mytemplate.html<form action="" method="post">    {% csrf_token %}    {{ aform.as_p }}    <input type="submit" name="{{aform.prefix}}" value="Submit" />    {{ bform.as_p }}    <input type="submit" name="{{bform.prefix}}" value="Submit" /></form>


matomo