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()
becomes inadequate when dealing with multiple forms. To properly address this scenario, the view must determine which form was submitted.
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.
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')
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!