如何在一个视图中处理两种表单? [英] How to process two forms in one view?

查看:105
本文介绍了如何在一个视图中处理两种表单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个模板中,我有两个完全不同的表单。如何在一个视图中处理它们?如何区分提交的表单?如何使用前缀来表示?或者也许最好写独立的意见?


问题

chriss

解决方案

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



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

 < form action =/ blog /method =POST> 
{{blog_form.as_p}}
< input type =hiddenname =form-typevalueblog-form/> <! - set type - >
< input type =submitvalue =提交/>
< / form>

...

< form action =/ blog /method =POST>
{{micro_form.as_p}}
< input type =hiddenname =form-typevaluemicro-form/> <! - set type - >
< input type =submitvalue =提交/>
< / form>

具有以下视图:

  def blog(request):
if request.method =='POST':
if request.POST ['form-type'] == ublog-form :#测试表单类型
form = BlogForm(request.POST)
...
else:
form = MicroForm(request.POST)
.. 。

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

...但是,我再次想到每个窗体一个视图(即使视图只接受POST)比试图做上述更简单。


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

解决方案

Personally, I'd use one view to handle each form's 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.

这篇关于如何在一个视图中处理两种表单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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