How to handle two forms in one view?

I have two completely different forms in one template. How to process them in one view? How can I tell which form was submitted? How can I use a prefix for this? Or is it better to write individual opinions?

welcomes
Chriss

+5
source share
3 answers

Personally, I use one view to process each form of POST.

Alternatively, you can use a hidden input element that indicates 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 such as:

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) , .

+5

ayaz, ,

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

If the two forms are completely different, then, of course, it will not hurt to be processed by two different types. Otherwise, you can use the "hidden input element" trick. Or you can always give each element submita unique name and distinguish in the view which form was submitted based on this.

0
source

All Articles