我有一个模板页期望两个表单。如果我只使用一种形式,就像下面这个典型的例子一样:

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

然而,如果我想处理多个表单,我如何让视图知道我只提交了其中一个表单,而不是另一个(即它仍然是请求。POST但我只想处理提交发生的形式)?


这是基于答案的解决方案,其中expectedphrase和bannedphrase是不同表单的提交按钮的名称,expectedphraseform和bannedphraseform是表单。

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

当前回答

你有几个选择:

在这两个表单的操作中放入不同的url。然后你会有两个不同的视图函数来处理这两个不同的表单。 从POST数据中读取提交按钮值。你可以知道哪个提交按钮被点击了:我如何构建多个提交按钮django form?

其他回答

我发现了一种非常有趣的方法,可以使用相同的视图从单个页面发送两个表单。我尝试了很多选择,但我只想要一个可以工作的。这是我发现的一些东西。但它只在一个页面上只有两个表单时才有效。

我正在使用只是尝试和方法,首先尝试第一种形式,如果那不工作,那就尝试第二种形式。这是非常有趣的,知道它工作得非常好。不要在可伸缩的应用程序上使用它,因为它会带来麻烦或可能会危及应用程序的安全,否则使用基于类的视图提交多个表单或为每个表单创建单独的视图。

def create_profile(request):
    if request.method=='POST':
        try:       
            biograph = Biography(name=name, email=email, full_name=full_name, slug_name=slug_name, short_bio=short_bio)
            biograph.save()

        except:
            social = SocialMedia(twitter=twitter, instagram=instagram, facebook=facebook, linkedin=linkedin, github=github)
            social.save()

根据@ybendana的回答:

同样,我们使用is_bound来检查表单是否能够进行验证。请参阅文档的这一部分:

绑定和未绑定的表单 Form实例可以绑定到一组数据,也可以不绑定。 如果它绑定到一组数据,它就能够验证该数据并将表单呈现为HTML,并在HTML中显示数据。 如果未绑定,则不能进行验证(因为没有数据要验证!),但仍然可以将空白表单呈现为HTML。

我们为表单对象和它们的详细信息使用元组列表,这允许更多的可扩展性和更少的重复。

但是,我们没有重写get(),而是重写get_context_data(),从而将一个新的空白表单实例(带前缀)插入到响应中作为任何请求的默认操作。在POST请求的上下文中,我们重写POST()方法以:

使用前缀检查每个表单是否已经提交 验证已提交的表单 使用cleaned_data处理有效的表单 通过覆盖上下文数据向响应返回任何无效表单

# views.py

class MultipleForms(TemplateResponseMixin, ContextMixin, View):

    form_list = [ # (context_key, formcls, prefix)
        ("form_a", FormA, "prefix_a"),
        ("form_b", FormB, "prefix_b"),
        ("form_c", FormC, "prefix_c"),
        ...
        ("form_x", FormX, "prefix_x"),
    ]

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        # Add blank forms to context with prefixes
        for context_key, formcls, prefix in self.form_list:
            context[context_key] = formcls(prefix=prefix)
        return context

    def post(self, request, *args, **kwargs):
        # Get object and context
        self.object = self.get_object()
        context = self.get_context_data(object=self.object)
        # Process forms
        for context_key, formcls, prefix in self.form_list:
            if prefix in request.POST:
                # Get the form object with prefix and pass it the POST data to \
                # validate and clean etc.
                form = formcls(request.POST, prefix=prefix)
                if form.is_bound:
                    # If the form is bound (i.e. it is capable of validation)  \
                    # check the validation
                    if form.is_valid():
                        # call the form's save() method or do whatever you     \
                        # want with form.cleaned_data
                        form.save()
                    else:
                        # overwrite context data for this form so that it is   \
                        # returned to the page with validation errors
                        context[context_key] = form
        # Pass context back to render_to_response() including any invalid forms
        return self.render_to_response(context)
        

这种方法允许在同一页面上重复表单条目,我发现@ybendana的答案并不适用。

我相信,将这个方法折叠到一个Mixin类中,将form_list对象作为一个属性,并像上面那样挂钩get_context_data()和post(),不会有更多的工作。

编辑:这个已经存在了。请参阅此存储库。

注: 这个方法需要TemplateResponseMixin来实现render_to_response(),需要ContextMixin来实现get_context_data()。要么使用这些mixin,要么使用源自它们的CBV。

if request.method == 'POST':
    expectedphraseform = ExpectedphraseForm(request.POST)
    bannedphraseform = BannedphraseForm(request.POST)
    if expectedphraseform.is_valid():
        expectedphraseform.save()
        return HttpResponse("Success")
    if bannedphraseform.is_valid():
        bannedphraseform.save()
        return HttpResponse("Success")
else:
    bannedphraseform = BannedphraseForm()
    expectedphraseform = ExpectedphraseForm()
return render(request, 'some.html',{'bannedphraseform':bannedphraseform, 'expectedphraseform':expectedphraseform})

这完全符合我的要求。这种方法有一个问题,即它验证了表单的两个错误。但工作完全没问题。

想要分享我的解决方案,Django表单没有被使用。 我在一个页面上有多个表单元素,我想使用一个视图来管理来自所有表单的所有POST请求。

我所做的是引入了一个不可见的输入标记,这样我就可以向视图传递一个参数来检查提交了哪个表单。

<form method="post" id="formOne">
    {% csrf_token %}
   <input type="hidden" name="form_type" value="formOne">

    .....
</form>

.....

<form method="post" id="formTwo">
    {% csrf_token %}
    <input type="hidden" name="form_type" value="formTwo">
   ....
</form>

views.py

def handlemultipleforms(request, template="handle/multiple_forms.html"):
    """
    Handle Multiple <form></form> elements
    """
    if request.method == 'POST':
        if request.POST.get("form_type") == 'formOne':
            #Handle Elements from first Form
        elif request.POST.get("form_type") == 'formTwo':
            #Handle Elements from second Form

如果你正在使用基于类的视图和不同的“动作”attrs方法,我的意思是

在这两个表单的操作中放入不同的url。然后你会有两个不同的视图函数来处理这两个不同的表单。

你可以使用重载get_context_data方法,e.x轻松处理来自不同表单的错误:

views.py:

class LoginView(FormView):
    form_class = AuthFormEdited
    success_url = '/'
    template_name = 'main/index.html'

    def dispatch(self, request, *args, **kwargs):
        return super(LoginView, self).dispatch(request, *args, **kwargs)

    ....

    def get_context_data(self, **kwargs):
        context = super(LoginView, self).get_context_data(**kwargs)
        context['login_view_in_action'] = True
        return context

class SignInView(FormView):
    form_class = SignInForm
    success_url = '/'
    template_name = 'main/index.html'

    def dispatch(self, request, *args, **kwargs):
        return super(SignInView, self).dispatch(request, *args, **kwargs)

    .....

    def get_context_data(self, **kwargs):
        context = super(SignInView, self).get_context_data(**kwargs)
        context['login_view_in_action'] = False
        return context

模板:

<div class="login-form">
<form action="/login/" method="post" role="form">
    {% csrf_token %}
    {% if login_view_in_action %}
        {% for e in form.non_field_errors %}
            <div class="alert alert-danger alert-dismissable">
                {{ e }}
                <a class="panel-close close" data-dismiss="alert">×</a>
            </div>
        {% endfor %}
    {% endif %}
    .....
    </form>
</div>

<div class="signin-form">
<form action="/registration/" method="post" role="form">
    {% csrf_token %}
    {% if not login_view_in_action %}
        {% for e in form.non_field_errors %}
            <div class="alert alert-danger alert-dismissable">
                {{ e }}
                <a class="panel-close close" data-dismiss="alert">×</a>
            </div>
        {% endfor %}
    {% endif %}
   ....
  </form>
</div>