Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to process two forms in one view?

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

like image 779
chriss Avatar asked Dec 25 '08 12:12

chriss


People also ask

How do I make multiple forms in Django?

Create a Django project and an app, I named the project "multipleFormHandle" and the app as "formhandlingapp". Do some basic stuff like including app in settings.py INSTALLED_APPS and include app's url in project's url. Now create forms.py in app and a "templates" folder in the app directory. Add home.

Can you have multiple forms on a page?

Yes. In general you can have many forms on the same page, which are being submitted by: <input type='submit' />

How do I put two forms in HTML?

How to make two forms side by side in html. style="float:left;" in the one and style="float:right;" in the other... 1. Wrap your forms in a <div> and apply float: left; to the wrapper: <div style="float:left;"> <form> input,submit etc </form> </div> 2.


2 Answers

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.

like image 185
Aaron Maenpaa Avatar answered Oct 05 '22 07:10

Aaron Maenpaa


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:
    ...
like image 26
user20955 Avatar answered Oct 05 '22 05:10

user20955