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

How to Handle Multiple Forms on a Single Page in Django?

Linda Hamilton
Release: 2024-11-28 19:43:12
Original
392 people have browsed it

How to Handle Multiple Forms on a Single Page in Django?

Handling Multiple Forms on a Single Page in Django

In Django, handling multiple forms on a single page requires careful consideration. The typical approach for handling a single form, as exemplified below:

if request.method == 'POST':
    form = AuthorForm(request.POST,)
    if form.is_valid():
        form.save()
        # do something.
else:
    form = AuthorForm()
Copy after login

becomes inadequate when dealing with multiple forms. To properly address this scenario, the view must determine which form was submitted.

Distinguishing Form Submissions

One approach is to include unique submit button values for each form. By parsing the POST data, the view can identify the clicked submit button and process the corresponding form.

Implementation Using Submit Button Values

For instance, consider two forms named expectedphraseform and bannedphraseform with submit buttons named expectedphrase and bannedphrase respectively. The following code snippet illustrates how to handle multiple forms using submit button values:

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')
Copy after login

By utilizing unique submit button values, the view can effectively differentiate between form submissions and process the intended form accordingly.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template