Proper way to handle multiple forms on one page in Django

后端 未结 10 2164
既然无缘
既然无缘 2020-11-22 09:19

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 = Au         


        
10条回答
  •  Happy的楠姐
    2020-11-22 09:39

    A method for future reference is something like this. bannedphraseform is the first form and expectedphraseform is the second. If the first one is hit, the second one is skipped (which is a reasonable assumption in this case):

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

提交回复
热议问题