Menu Close

How to handle multiple forms on one page in Python Django?

To handle multiple forms on one page in Python Django, we can set the forms to use in our views.

For instance, we write

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

in our view to set different forms to use according to different conditions.

We use if statements to check request methods and form validation to assign which form to render in the page.

Posted in Python, Python Answers