在 Django 的一个页面上处理多个表单的正确方法 [英] Proper way to handle multiple forms on one page in Django

查看:42
本文介绍了在 Django 的一个页面上处理多个表单的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要两种形式的模板页面.如果我只使用一种形式,就像这个典型的例子一样:

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

但是,如果我想处理多个表单,我如何让视图知道我只提交了一个表单而不是另一个(即它仍然是 request.POST 但我只想处理表单哪个提交发生了)?

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

这是基于答案的解决方案,其中expectedphrasebannedphrase 是不同表单的提交按钮的名称,expectedphraseformbannedphraseform 是形式.

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

推荐答案

您有几个选择:

  1. 在两个表单的操作中放置不同的 URL.然后你会有两个不同的视图函数来处理这两种不同的表单.

  1. Put different URLs in the action for the two forms. Then you'll have two different view functions to deal with the two different forms.

从 POST 数据中读取提交按钮值.您可以判断点击了哪个提交按钮:如何构建多个提交按钮 django 表单?

Read the submit button values from the POST data. You can tell which submit button was clicked: How can I build multiple submit buttons django form?

这篇关于在 Django 的一个页面上处理多个表单的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆