Home >Backend Development >Python Tutorial >How to Handle Multiple Forms on a Single Django Page?

How to Handle Multiple Forms on a Single Django Page?

Susan Sarandon
Susan SarandonOriginal
2024-11-30 03:49:18907browse

How to Handle Multiple Forms on a Single Django Page?

Handling Multiple Forms on a Single Page in Django

When working with multiple forms on a single Django template, it's essential to determine which form is being submitted to avoid processing both forms simultaneously. The primary challenge lies in identifying the desired form within the POST data.

Multiple Form Options

There are several approaches to addressing this issue:

  • Separate URLs: Assign distinct URLs to each form. This results in multiple view functions handling the forms individually.
  • Submit Button Values: Examine the submit button values in the POST data to determine which button was used.

Example Solution

Consider the following scenario where we have two forms on a page: expectedphraseform and bannedphraseform. To handle their submission, we employ the following code:

if request.method == 'POST':
    if 'bannedphrase' in request.POST:
        bannedphraseform = BannedPhraseForm(request.POST, prefix='banned')
        if bannedphraseform.is_valid():
            bannedphraseform.save()
        expectedphraseform = ExpectedPhraseForm(prefix='expected')
    elif 'expectedphrase' in request.POST:
        expectedphraseform = ExpectedPhraseForm(request.POST, prefix='expected')
        if expectedphraseform.is_valid():
            expectedphraseform.save()
        bannedphraseform = BannedPhraseForm(prefix='banned')
else:
    bannedphraseform = BannedPhraseForm(prefix='banned')
    expectedphraseform = ExpectedPhraseForm(prefix='expected')

In this example, we check the POST data for the submit button values. Based on the value, we instantiate the corresponding form and attempt to save it. The prefix ensures that the submitted data is correctly bound to the form.

The above is the detailed content of How to Handle Multiple Forms on a Single Django Page?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn