views:

438

answers:

3

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

+4  A: 

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.

Aaron Maenpaa
A: 

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.

ayaz
+2  A: 

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