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

How Can I Handle Multiple Forms on a Single Django Page?

Barbara Streisand
Barbara StreisandOriginal
2024-11-19 04:22:02870browse

How Can I Handle Multiple Forms on a Single Django Page?

Handling Multiple Forms on a Single Django Page

When working with multiple forms on a single Django template page, identifying which form has been submitted can be a challenge. This question addresses the issue and provides a solution using form prefixes.

If a single form is being used, the standard approach is to check the request method and process the form accordingly:

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

However, with multiple forms, determining which one to process while only receiving a single request.POST object can be tricky. The solution proposed in this question involves using form prefixes, allowing the view to differentiate between the forms.

The provided solution creates two form instances, one for each expected form, and then inspects the submit button values in the POST data. By using prefixes in the form names and submit button names, the code can determine which form was submitted:

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

This approach effectively handles multiple forms on a single Django page, ensuring that only the intended form is processed and validated.

The above is the detailed content of How Can I 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