如何在一个视图中处理两个表单?

[英]How to process two forms in one view?


I have two completely different forms in one template. How to process them in one view? How can I distinguish which of the forms was submitted? How can I use prefix to acomplish that? Or maybe it's better to write separate views?

regards
chriss

我在一个模板中有两种完全不同的形式。如何在一个视图中处理它们?如何区分提交的表格?我怎样才能使用前缀来实现呢?或者也许最好写单独的视图?尊重克里斯

3 个解决方案

#1


5  

Personally, I'd use one view to handle each form's POST.

就个人而言,我会使用一个视图来处理每个表单的POST。

On the other hand, you could use a hidden input element that indicate which form was used

另一方面,您可以使用隐藏的输入元素来指示使用哪种表单

<form action="/blog/" method="POST">
    {{ blog_form.as_p }}
    <input type="hidden" name="form-type" value"blog-form" /> <!-- set type -->
    <input type="submit" value="Submit" />
</form>

... 

<form action="/blog/" method="POST">
    {{ micro_form.as_p }}
    <input type="hidden" name="form-type" value"micro-form" /> <!-- set type -->
    <input type="submit" value="Submit" />
</form>

With a view like:

有这样的观点:

def blog(request):
    if request.method == 'POST':
        if request.POST['form-type'] == u"blog-form":   # test the form type
            form = BlogForm(request.POST) 
            ...
        else:
            form = MicroForm(request.POST)
            ...

    return render_to_response('blog.html', {
        'blog_form': BlogForm(),
        'micro_form': MicroForm(),
    })

... but once again, I think one view per form (even if the view only accepts POSTs) is simpler than trying to do the above.

...但是再一次,我认为每个表单的一个视图(即使视图只接受POST)比尝试执行上述操作简单。

#2


4  

like ayaz said, you should give unique name to form submit button

像ayaz所说,你应该给表单提交按钮的唯一名称

<form action="." method="post">
......
<input type="submit" name="form1">
</form>


<form action="." method="post">
......
<input type="submit" name="form2">
</form>


#view

if "form1" in request.POST:
    ...
if "form2" in request.POST:
    ...

#3


0  

If the two forms are completely different, it will certainly not hurt to have them be handled by two different views. Otherwise, you may use the 'hidden input element' trick zacherates has touched upon. Or, you could always give each submit element a unique name, and differentiate in the view which form was submitted based on that.

如果两种形式完全不同,那么让它们由两种不同的视图处理肯定不会有害。否则,您可以使用zacherates所触及的“隐藏输入元素”技巧。或者,您始终可以为每个提交元素指定唯一名称,并在视图中区分基于该提交的表单。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2008/12/25/cc165b5dd1c4500f6c22a4c36434fb2a.html



 
© 2014-2018 ITdaan.com 粤ICP备14056181号