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

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

问题描述

我在一个模板中有两种完全不同的形式.如何在一个视图中处理它们?如何区分提交的是哪个表格?我如何使用前缀来完成它?或者也许最好编写单独的视图?

问候
克里斯

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

推荐答案

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

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>

视图如下:

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

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

... 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天全站免登陆