How to process two forms in one view?

可紊 提交于 2019-12-18 13:31:27

问题


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


回答1:


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.




回答2:


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

<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:


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.



来源:https://stackoverflow.com/questions/392784/how-to-process-two-forms-in-one-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!