1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Proper way to handle multiple forms on one page in Django

Discussão em 'Python' iniciado por Stack, Setembro 14, 2024.

  1. Stack

    Stack Membro Participativo

    I have a template page expecting two forms. If I just use one form, things are fine as in this typical example:

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


    If I want to work with multiple forms however, how do I let the view know that I'm submitting only one of the forms and not the other (i.e. it's still request.POST but I only want to process the form for which the submit happened)?


    This is the solution based on the answer where expectedphrase and bannedphrase are the names of the submit buttons for the different forms and expectedphraseform and bannedphraseform are the forms.

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

    Continue reading...

Compartilhe esta Página