How to process two forms in one view?

后端 未结 3 1649
心在旅途
心在旅途 2021-01-01 02:38

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 acomp

相关标签:
3条回答
  • 2021-01-01 03:18

    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.

    0 讨论(0)
  • 2021-01-01 03:27

    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:
        ...
    
    0 讨论(0)
  • 2021-01-01 03:42

    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.

    0 讨论(0)
提交回复
热议问题